Clover icon

jackson-databind

  1. Project Clover database Thu Jan 5 2023 23:38:46 MST
  2. Package com.fasterxml.jackson.databind

File ObjectMapper.java

 

Coverage histogram

../../../../img/srcFileCovDistChart7.png
50% of files have more coverage

Code metrics

140
523
202
3
3,010
1,359
299
0.57
2.59
67.33
1.48

Classes

Class Line # Actions
ObjectMapper 54 508 288 295
0.6479713364.8%
ObjectMapper.DefaultTyping 73 0 0 0
-1.0 -
ObjectMapper.DefaultTypeResolverBuilder 117 15 11 0
1.0100%
 

Contributing tests

This file is covered by 2005 tests. .

Source view

1    package com.fasterxml.jackson.databind;
2   
3    import java.io.*;
4    import java.lang.reflect.Type;
5    import java.net.URL;
6    import java.text.DateFormat;
7    import java.util.*;
8    import java.util.concurrent.ConcurrentHashMap;
9   
10    import com.fasterxml.jackson.annotation.*;
11    import com.fasterxml.jackson.core.*;
12    import com.fasterxml.jackson.core.io.SegmentedStringWriter;
13    import com.fasterxml.jackson.core.io.SerializedString;
14    import com.fasterxml.jackson.core.type.ResolvedType;
15    import com.fasterxml.jackson.core.type.TypeReference;
16    import com.fasterxml.jackson.core.util.*;
17    import com.fasterxml.jackson.databind.cfg.BaseSettings;
18    import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
19    import com.fasterxml.jackson.databind.cfg.MapperConfig;
20    import com.fasterxml.jackson.databind.deser.*;
21    import com.fasterxml.jackson.databind.introspect.*;
22    import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
23    import com.fasterxml.jackson.databind.jsontype.*;
24    import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
25    import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
26    import com.fasterxml.jackson.databind.node.*;
27    import com.fasterxml.jackson.databind.ser.*;
28    import com.fasterxml.jackson.databind.type.*;
29    import com.fasterxml.jackson.databind.util.RootNameLookup;
30    import com.fasterxml.jackson.databind.util.StdDateFormat;
31    import com.fasterxml.jackson.databind.util.TokenBuffer;
32   
33    /**
34    * This mapper (or, data binder, or codec) provides functionality for
35    * converting between Java objects (instances of JDK provided core classes,
36    * beans), and matching JSON constructs.
37    * It will use instances of {@link JsonParser} and {@link JsonGenerator}
38    * for implementing actual reading/writing of JSON.
39    *<p>
40    * The main conversion API is defined in {@link ObjectCodec}, so that
41    * implementation details of this class need not be exposed to
42    * streaming parser and generator classes.
43    *<p>
44    * Note on caching: root-level deserializers are always cached, and accessed
45    * using full (generics-aware) type information. This is different from
46    * caching of referenced types, which is more limited and is done only
47    * for a subset of all deserializer types. The main reason for difference
48    * is that at root-level there is no incoming reference (and hence no
49    * referencing property, no referral information or annotations to
50    * produce differing deserializers), and that the performance impact
51    * greatest at root level (since it'll essentially cache the full
52    * graph of deserializers involved).
53    */
 
54    public class ObjectMapper
55    extends ObjectCodec
56    implements Versioned,
57    java.io.Serializable // as of 2.1
58    {
59    private static final long serialVersionUID = 1L;
60   
61    /*
62    /**********************************************************
63    /* Helper classes, enums
64    /**********************************************************
65    */
66   
67    /**
68    * Enumeration used with {@link ObjectMapper#enableDefaultTyping()}
69    * to specify what kind of types (classes) default typing should
70    * be used for. It will only be used if no explicit type information
71    * is found, but this enumeration further limits subset of those types.
72    */
 
73    public enum DefaultTyping {
74    /**
75    * This value means that only properties that have
76    * {@link java.lang.Object} as declared type (including
77    * generic types without explicit type) will use default
78    * typing.
79    */
80    JAVA_LANG_OBJECT,
81   
82    /**
83    * Value that means that default typing will be used for
84    * properties with declared type of {@link java.lang.Object}
85    * or an abstract type (abstract class or interface).
86    * Note that this does <b>not</b> include array types.
87    */
88    OBJECT_AND_NON_CONCRETE,
89   
90    /**
91    * Value that means that default typing will be used for
92    * all types covered by {@link #OBJECT_AND_NON_CONCRETE}
93    * plus all array types for them.
94    */
95    NON_CONCRETE_AND_ARRAYS,
96   
97    /**
98    * Value that means that default typing will be used for
99    * all non-final types, with exception of small number of
100    * "natural" types (String, Boolean, Integer, Double), which
101    * can be correctly inferred from JSON; as well as for
102    * all arrays of non-final types.
103    */
104    NON_FINAL
105    }
106   
107    /**
108    * Customized {@link TypeResolverBuilder} that provides type resolver builders
109    * used with so-called "default typing"
110    * (see {@link ObjectMapper#enableDefaultTyping()} for details).
111    *<p>
112    * Type resolver construction is based on configuration: implementation takes care
113    * of only providing builders in cases where type information should be applied.
114    * This is important since build calls may be sent for any and all types, and
115    * type information should NOT be applied to all of them.
116    */
 
117    public static class DefaultTypeResolverBuilder
118    extends StdTypeResolverBuilder
119    implements java.io.Serializable
120    {
121    private static final long serialVersionUID = 1L;
122   
123    /**
124    * Definition of what types is this default typer valid for.
125    */
126    protected final DefaultTyping _appliesFor;
127   
 
128  78 toggle public DefaultTypeResolverBuilder(DefaultTyping t) {
129  78 _appliesFor = t;
130    }
131   
 
132  292 toggle @Override
133    public TypeDeserializer buildTypeDeserializer(DeserializationConfig config,
134    JavaType baseType, Collection<NamedType> subtypes)
135    {
136  292 return useForType(baseType) ? super.buildTypeDeserializer(config, baseType, subtypes) : null;
137    }
138   
 
139  262 toggle @Override
140    public TypeSerializer buildTypeSerializer(SerializationConfig config,
141    JavaType baseType, Collection<NamedType> subtypes)
142    {
143  262 return useForType(baseType) ? super.buildTypeSerializer(config, baseType, subtypes) : null;
144    }
145   
146    /**
147    * Method called to check if the default type handler should be
148    * used for given type.
149    * Note: "natural types" (String, Boolean, Integer, Double) will never
150    * use typing; that is both due to them being concrete and final,
151    * and since actual serializers and deserializers will also ignore any
152    * attempts to enforce typing.
153    */
 
154  554 toggle public boolean useForType(JavaType t)
155    {
156  554 switch (_appliesFor) {
157  34 case NON_CONCRETE_AND_ARRAYS:
158  44 while (t.isArrayType()) {
159  10 t = t.getContentType();
160    }
161    // fall through
162  192 case OBJECT_AND_NON_CONCRETE:
163  226 return (t.getRawClass() == Object.class) || !t.isConcrete();
164  290 case NON_FINAL:
165  310 while (t.isArrayType()) {
166  20 t = t.getContentType();
167    }
168  290 return !t.isFinal(); // includes Object.class
169  38 default:
170    //case JAVA_LANG_OBJECT:
171  38 return (t.getRawClass() == Object.class);
172    }
173    }
174    }
175   
176    /*
177    /**********************************************************
178    /* Internal constants, singletons
179    /**********************************************************
180    */
181   
182    // Quick little shortcut, to avoid having to use global TypeFactory instance...
183    private final static JavaType JSON_NODE_TYPE = SimpleType.constructUnsafe(JsonNode.class);
184   
185    /* !!! 03-Apr-2009, tatu: Should try to avoid direct reference... but not
186    * sure what'd be simple and elegant way. So until then:
187    */
188    protected final static ClassIntrospector DEFAULT_INTROSPECTOR = BasicClassIntrospector.instance;
189   
190    // 16-May-2009, tatu: Ditto ^^^
191    protected final static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR = new JacksonAnnotationIntrospector();
192   
193    protected final static VisibilityChecker<?> STD_VISIBILITY_CHECKER = VisibilityChecker.Std.defaultInstance();
194   
195    protected final static PrettyPrinter _defaultPrettyPrinter = new DefaultPrettyPrinter();
196   
197    /**
198    * Base settings contain defaults used for all {@link ObjectMapper}
199    * instances.
200    */
201    protected final static BaseSettings DEFAULT_BASE = new BaseSettings(DEFAULT_INTROSPECTOR,
202    DEFAULT_ANNOTATION_INTROSPECTOR, STD_VISIBILITY_CHECKER, null, TypeFactory.defaultInstance(),
203    null, StdDateFormat.instance, null,
204    Locale.getDefault(),
205    // TimeZone.getDefault()
206    TimeZone.getTimeZone("GMT"),
207    Base64Variants.getDefaultVariant() // 2.1
208    );
209   
210    /*
211    /**********************************************************
212    /* Configuration settings, shared
213    /**********************************************************
214    */
215   
216    /**
217    * Factory used to create {@link JsonParser} and {@link JsonGenerator}
218    * instances as necessary.
219    */
220    protected final JsonFactory _jsonFactory;
221   
222    /**
223    * Specific factory used for creating {@link JavaType} instances;
224    * needed to allow modules to add more custom type handling
225    * (mostly to support types of non-Java JVM languages)
226    */
227    protected TypeFactory _typeFactory;
228   
229    /**
230    * Provider for values to inject in deserialized POJOs.
231    */
232    protected InjectableValues _injectableValues;
233   
234    /**
235    * Thing used for registering sub-types, resolving them to
236    * super/sub-types as needed.
237    */
238    protected SubtypeResolver _subtypeResolver;
239   
240    /**
241    * Cache for root names used when root-wrapping is enabled.
242    */
243    protected final RootNameLookup _rootNames;
244   
245    /*
246    /**********************************************************
247    /* Configuration settings: mix-in annotations
248    /**********************************************************
249    */
250   
251    /**
252    * Mapping that defines how to apply mix-in annotations: key is
253    * the type to received additional annotations, and value is the
254    * type that has annotations to "mix in".
255    *<p>
256    * Annotations associated with the value classes will be used to
257    * override annotations of the key class, associated with the
258    * same field or method. They can be further masked by sub-classes:
259    * you can think of it as injecting annotations between the target
260    * class and its sub-classes (or interfaces)
261    */
262    protected final HashMap<ClassKey,Class<?>> _mixInAnnotations
263    = new HashMap<ClassKey,Class<?>>();
264   
265    /*
266    /**********************************************************
267    /* Configuration settings, serialization
268    /**********************************************************
269    */
270   
271    /**
272    * Configuration object that defines basic global
273    * settings for the serialization process
274    */
275    protected SerializationConfig _serializationConfig;
276   
277    /**
278    * Object that manages access to serializers used for serialization,
279    * including caching.
280    * It is configured with {@link #_serializerFactory} to allow
281    * for constructing custom serializers.
282    *<p>
283    * Note: while serializers are only exposed {@link SerializerProvider},
284    * mappers and readers need to access additional API defined by
285    * {@link DefaultSerializerProvider}
286    */
287    protected DefaultSerializerProvider _serializerProvider;
288   
289    /**
290    * Serializer factory used for constructing serializers.
291    */
292    protected SerializerFactory _serializerFactory;
293   
294    /*
295    /**********************************************************
296    /* Configuration settings, deserialization
297    /**********************************************************
298    */
299   
300    /**
301    * Configuration object that defines basic global
302    * settings for the serialization process
303    */
304    protected DeserializationConfig _deserializationConfig;
305   
306    /**
307    * Blueprint context object; stored here to allow custom
308    * sub-classes. Contains references to objects needed for
309    * deserialization construction (cache, factory).
310    */
311    protected DefaultDeserializationContext _deserializationContext;
312   
313    /*
314    /**********************************************************
315    /* Caching
316    /**********************************************************
317    */
318   
319    /* Note: handling of serializers and deserializers is not symmetric;
320    * and as a result, only root-level deserializers can be cached here.
321    * This is mostly because typing and resolution for deserializers is
322    * fully static; whereas it is quite dynamic for serialization.
323    */
324   
325    /**
326    * We will use a separate main-level Map for keeping track
327    * of root-level deserializers. This is where most succesful
328    * cache lookups get resolved.
329    * Map will contain resolvers for all kinds of types, including
330    * container types: this is different from the component cache
331    * which will only cache bean deserializers.
332    *<p>
333    * Given that we don't expect much concurrency for additions
334    * (should very quickly converge to zero after startup), let's
335    * explicitly define a low concurrency setting.
336    *<p>
337    * Since version 1.5, these may are either "raw" deserializers (when
338    * no type information is needed for base type), or type-wrapped
339    * deserializers (if it is needed)
340    */
341    final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers
342    = new ConcurrentHashMap<JavaType, JsonDeserializer<Object>>(64, 0.6f, 2);
343   
344    /*
345    /**********************************************************
346    /* Life-cycle: constructing instance
347    /**********************************************************
348    */
349   
350    /**
351    * Default constructor, which will construct the default
352    * {@link JsonFactory} as necessary, use
353    * {@link SerializerProvider} as its
354    * {@link SerializerProvider}, and
355    * {@link BeanSerializerFactory} as its
356    * {@link SerializerFactory}.
357    * This means that it
358    * can serialize all standard JDK types, as well as regular
359    * Java Beans (based on method names and Jackson-specific annotations),
360    * but does not support JAXB annotations.
361    */
 
362  2459 toggle public ObjectMapper()
363    {
364  2459 this(null, null, null);
365    }
366   
367    /**
368    * Constructs instance that uses specified {@link JsonFactory}
369    * for constructing necessary {@link JsonParser}s and/or
370    * {@link JsonGenerator}s.
371    */
 
372  25 toggle public ObjectMapper(JsonFactory jf)
373    {
374  25 this(jf, null, null);
375    }
376   
377    /**
378    * Copy-constructor, mostly used to support {@link #copy}.
379    *
380    * @since 2.1
381    */
 
382  2 toggle protected ObjectMapper(ObjectMapper src)
383    {
384  2 _jsonFactory = src._jsonFactory.copy();
385  2 _jsonFactory.setCodec(this);
386  2 _subtypeResolver = src._subtypeResolver;
387  2 _rootNames = new RootNameLookup();
388  2 _typeFactory = src._typeFactory;
389  2 _serializationConfig = src._serializationConfig;
390  2 HashMap<ClassKey,Class<?>> mixins = new HashMap<ClassKey,Class<?>>(src._mixInAnnotations);
391  2 _serializationConfig = new SerializationConfig(src._serializationConfig, mixins);
392  2 _deserializationConfig = new DeserializationConfig(src._deserializationConfig, mixins);
393  2 _serializerProvider = src._serializerProvider;
394  2 _deserializationContext = src._deserializationContext;
395   
396    // Default serializer factory is stateless, can just assign
397  2 _serializerFactory = src._serializerFactory;
398    }
399   
400    /**
401    * Constructs instance that uses specified {@link JsonFactory}
402    * for constructing necessary {@link JsonParser}s and/or
403    * {@link JsonGenerator}s, and uses given providers for accessing
404    * serializers and deserializers.
405    *
406    * @param jf JsonFactory to use: if null, a new {@link MappingJsonFactory} will be constructed
407    * @param sp SerializerProvider to use: if null, a {@link SerializerProvider} will be constructed
408    * @param dc Blueprint deserialization context instance to use for creating
409    * actual context objects; if null, will construct standard
410    * {@link DeserializationContext}
411    */
 
412  2484 toggle public ObjectMapper(JsonFactory jf,
413    DefaultSerializerProvider sp, DefaultDeserializationContext dc)
414    {
415    /* 02-Mar-2009, tatu: Important: we MUST default to using
416    * the mapping factory, otherwise tree serialization will
417    * have problems with POJONodes.
418    * 03-Jan-2010, tatu: and obviously we also must pass 'this',
419    * to create actual linking.
420    */
421  2484 if (jf == null) {
422  2459 _jsonFactory = new MappingJsonFactory(this);
423    } else {
424  25 _jsonFactory = jf;
425  25 if (jf.getCodec() == null) { // as per [JACKSON-741]
426  25 _jsonFactory.setCodec(this);
427    }
428    }
429  2484 _subtypeResolver = new StdSubtypeResolver();
430  2484 _rootNames = new RootNameLookup();
431    // and default type factory is shared one
432  2484 _typeFactory = TypeFactory.defaultInstance();
433  2484 _serializationConfig = new SerializationConfig(DEFAULT_BASE,
434    _subtypeResolver, _mixInAnnotations);
435  2484 _deserializationConfig = new DeserializationConfig(DEFAULT_BASE,
436    _subtypeResolver, _mixInAnnotations);
437  2484 _serializerProvider = (sp == null) ? new DefaultSerializerProvider.Impl() : sp;
438  2484 _deserializationContext = (dc == null) ?
439    new DefaultDeserializationContext.Impl(BeanDeserializerFactory.instance) : dc;
440   
441    // Default serializer factory is stateless, can just assign
442  2484 _serializerFactory = BeanSerializerFactory.instance;
443    }
444   
445    /**
446    * Method for creating a new {@link ObjectMapper} instance that
447    * has same initial configuration as this instance. Note that this
448    * also requires making a copy of the underlying {@link JsonFactory}
449    * instance.
450    *<p>
451    * Method is typically
452    * used when multiple, differently configured mappers are needed.
453    * Although configuration is shared, cached serializers and deserializers
454    * are NOT shared, which means that the new instance may be re-configured
455    * before use; meaning that it behaves the same way as if an instance
456    * was constructed from scratch.
457    *
458    * @since 2.1
459    */
 
460  2 toggle public ObjectMapper copy()
461    {
462  2 _checkInvalidCopy(ObjectMapper.class);
463  2 return new ObjectMapper(this);
464    }
465   
466    /**
467    * @since 2.1
468    * @param exp
469    */
 
470  2 toggle protected void _checkInvalidCopy(Class<?> exp)
471    {
472  2 if (getClass() != exp) {
473  0 throw new IllegalStateException("Failed copy(): "+getClass().getName()
474    +" (version: "+version()+") does not override copy(); it has to");
475    }
476    }
477   
478    /*
479    /**********************************************************
480    /* Versioned impl
481    /**********************************************************
482    */
483   
484    /**
485    * Method that will return version information stored in and read from jar
486    * that contains this class.
487    */
 
488  4 toggle @Override
489    public Version version() {
490  4 return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
491    }
492   
493    /*
494    /**********************************************************
495    /* Module registration, discovery
496    /**********************************************************
497    */
498   
499    /**
500    * Method for registering a module that can extend functionality
501    * provided by this mapper; for example, by adding providers for
502    * custom serializers and deserializers.
503    *
504    * @param module Module to register
505    */
 
506  150 toggle public ObjectMapper registerModule(Module module)
507    {
508    /* Let's ensure we have access to name and version information,
509    * even if we do not have immediate use for either. This way we know
510    * that they will be available from beginning
511    */
512  150 String name = module.getModuleName();
513  150 if (name == null) {
514  0 throw new IllegalArgumentException("Module without defined name");
515    }
516  150 Version version = module.version();
517  150 if (version == null) {
518  0 throw new IllegalArgumentException("Module without defined version");
519    }
520   
521  150 final ObjectMapper mapper = this;
522   
523    // And then call registration
524  150 module.setupModule(new Module.SetupContext()
525    {
526    // // // Accessors
527   
 
528  0 toggle @Override
529    public Version getMapperVersion() {
530  0 return version();
531    }
532   
 
533  4 toggle @SuppressWarnings("unchecked")
534    @Override
535    public <C extends ObjectCodec> C getOwner() {
536    // why do we need the cast here?!?
537  4 return (C) mapper;
538    }
539   
 
540  0 toggle @Override
541    public TypeFactory getTypeFactory() {
542  0 return _typeFactory;
543    }
544   
 
545  0 toggle @Override
546    public boolean isEnabled(MapperFeature f) {
547  0 return mapper.isEnabled(f);
548    }
549   
 
550  0 toggle @Override
551    public boolean isEnabled(DeserializationFeature f) {
552  0 return mapper.isEnabled(f);
553    }
554   
 
555  0 toggle @Override
556    public boolean isEnabled(SerializationFeature f) {
557  0 return mapper.isEnabled(f);
558    }
559   
 
560  0 toggle @Override
561    public boolean isEnabled(JsonFactory.Feature f) {
562  0 return mapper.isEnabled(f);
563    }
564   
 
565  0 toggle @Override
566    public boolean isEnabled(JsonParser.Feature f) {
567  0 return mapper.isEnabled(f);
568    }
569   
 
570  0 toggle @Override
571    public boolean isEnabled(JsonGenerator.Feature f) {
572  0 return mapper.isEnabled(f);
573    }
574   
575    // // // Methods for registering handlers: deserializers
576   
 
577  42 toggle @Override
578    public void addDeserializers(Deserializers d) {
579  42 DeserializerFactory df = mapper._deserializationContext._factory.withAdditionalDeserializers(d);
580  42 mapper._deserializationContext = mapper._deserializationContext.with(df);
581    }
582   
 
583  4 toggle @Override
584    public void addKeyDeserializers(KeyDeserializers d) {
585  4 DeserializerFactory df = mapper._deserializationContext._factory.withAdditionalKeyDeserializers(d);
586  4 mapper._deserializationContext = mapper._deserializationContext.with(df);
587    }
588   
 
589  16 toggle @Override
590    public void addBeanDeserializerModifier(BeanDeserializerModifier modifier) {
591  16 DeserializerFactory df = mapper._deserializationContext._factory.withDeserializerModifier(modifier);
592  16 mapper._deserializationContext = mapper._deserializationContext.with(df);
593    }
594   
595    // // // Methods for registering handlers: serializers
596   
 
597  40 toggle @Override
598    public void addSerializers(Serializers s) {
599  40 mapper._serializerFactory = mapper._serializerFactory.withAdditionalSerializers(s);
600    }
601   
 
602  2 toggle @Override
603    public void addKeySerializers(Serializers s) {
604  2 mapper._serializerFactory = mapper._serializerFactory.withAdditionalKeySerializers(s);
605    }
606   
 
607  20 toggle @Override
608    public void addBeanSerializerModifier(BeanSerializerModifier modifier) {
609  20 mapper._serializerFactory = mapper._serializerFactory.withSerializerModifier(modifier);
610    }
611   
612    // // // Methods for registering handlers: other
613   
 
614  8 toggle @Override
615    public void addAbstractTypeResolver(AbstractTypeResolver resolver) {
616  8 DeserializerFactory df = mapper._deserializationContext._factory.withAbstractTypeResolver(resolver);
617  8 mapper._deserializationContext = mapper._deserializationContext.with(df);
618    }
619   
 
620  0 toggle @Override
621    public void addTypeModifier(TypeModifier modifier) {
622  0 TypeFactory f = mapper._typeFactory;
623  0 f = f.withModifier(modifier);
624  0 mapper.setTypeFactory(f);
625    }
626   
 
627  28 toggle @Override
628    public void addValueInstantiators(ValueInstantiators instantiators) {
629  28 DeserializerFactory df = mapper._deserializationContext._factory.withValueInstantiators(instantiators);
630  28 mapper._deserializationContext = mapper._deserializationContext.with(df);
631    }
632   
 
633  0 toggle @Override
634    public void setClassIntrospector(ClassIntrospector ci) {
635  0 mapper._deserializationConfig = mapper._deserializationConfig.with(ci);
636  0 mapper._serializationConfig = mapper._serializationConfig.with(ci);
637    }
638   
 
639  0 toggle @Override
640    public void insertAnnotationIntrospector(AnnotationIntrospector ai) {
641  0 mapper._deserializationConfig = mapper._deserializationConfig.withInsertedAnnotationIntrospector(ai);
642  0 mapper._serializationConfig = mapper._serializationConfig.withInsertedAnnotationIntrospector(ai);
643    }
644   
 
645  0 toggle @Override
646    public void appendAnnotationIntrospector(AnnotationIntrospector ai) {
647  0 mapper._deserializationConfig = mapper._deserializationConfig.withAppendedAnnotationIntrospector(ai);
648  0 mapper._serializationConfig = mapper._serializationConfig.withAppendedAnnotationIntrospector(ai);
649    }
650   
 
651  0 toggle @Override
652    public void registerSubtypes(Class<?>... subtypes) {
653  0 mapper.registerSubtypes(subtypes);
654    }
655   
 
656  2 toggle @Override
657    public void registerSubtypes(NamedType... subtypes) {
658  2 mapper.registerSubtypes(subtypes);
659    }
660   
 
661  2 toggle @Override
662    public void setMixInAnnotations(Class<?> target, Class<?> mixinSource) {
663  2 mapper.addMixInAnnotations(target, mixinSource);
664    }
665   
 
666  0 toggle @Override
667    public void addDeserializationProblemHandler(DeserializationProblemHandler handler) {
668  0 mapper.addHandler(handler);
669    }
670    });
671  150 return this;
672    }
673   
674    /**
675    * Convenience method for registering specified modules in order;
676    * functionally equivalent to:
677    *<pre>
678    * for (Module module : modules) {
679    * registerModule(module);
680    * }
681    *</pre>
682    *
683    * @since 2.2
684    */
 
685  0 toggle public ObjectMapper registerModules(Module... modules)
686    {
687  0 for (Module module : modules) {
688  0 registerModule(module);
689    }
690  0 return this;
691    }
692   
693    /**
694    * Convenience method for registering specified modules in order;
695    * functionally equivalent to:
696    *<pre>
697    * for (Module module : modules) {
698    * registerModule(module);
699    * }
700    *</pre>
701    *
702    * @since 2.2
703    */
 
704  0 toggle public ObjectMapper registerModules(Iterable<Module> modules)
705    {
706  0 for (Module module : modules) {
707  0 registerModule(module);
708    }
709  0 return this;
710    }
711   
712    /**
713    * Method for locating available methods, using JDK {@link ServiceLoader}
714    * facility, along with module-provided SPI.
715    *<p>
716    * Note that method does not do any caching, so calls should be considered
717    * potentially expensive.
718    *
719    * @since 2.2
720    */
 
721  0 toggle public static List<Module> findModules() {
722  0 return findModules(null);
723    }
724   
725    /**
726    * Method for locating available methods, using JDK {@link ServiceLoader}
727    * facility, along with module-provided SPI.
728    *<p>
729    * Note that method does not do any caching, so calls should be considered
730    * potentially expensive.
731    *
732    * @since 2.2
733    */
 
734  0 toggle public static List<Module> findModules(ClassLoader classLoader)
735    {
736  0 ArrayList<Module> modules = new ArrayList<Module>();
737  0 ServiceLoader<Module> loader = (classLoader == null) ?
738    ServiceLoader.load(Module.class) : ServiceLoader.load(Module.class, classLoader);
739  0 for (Module module : loader) {
740  0 modules.add(module);
741    }
742  0 return modules;
743    }
744   
745    /**
746    * Convenience method that is functionally equivalent to:
747    *<code>
748    * mapper.registerModules(mapper.findModules());
749    *<code>
750    *<p>
751    * As with {@link #findModules()}, no caching is done for modules, so care
752    * needs to be taken to either create and share a single mapper instance;
753    * or to cache introspected set of modules.
754    *
755    * @since 2.2
756    */
 
757  0 toggle public ObjectMapper findAndRegisterModules() {
758  0 return registerModules(findModules());
759    }
760   
761    /*
762    /**********************************************************
763    /* Configuration: main config object access
764    /**********************************************************
765    */
766   
767    /**
768    * Method that returns the shared default {@link SerializationConfig}
769    * object that defines configuration settings for serialization.
770    *<p>
771    * Note that since instances are immutable, you can NOT change settings
772    * by accessing an instance and calling methods: this will simply create
773    * new instance of config object.
774    */
 
775  1483 toggle public SerializationConfig getSerializationConfig() {
776  1483 return _serializationConfig;
777    }
778   
779    /**
780    * Method that returns
781    * the shared default {@link DeserializationConfig} object
782    * that defines configuration settings for deserialization.
783    *<p>
784    * Note that since instances are immutable, you can NOT change settings
785    * by accessing an instance and calling methods: this will simply create
786    * new instance of config object.
787    */
 
788  2170 toggle public DeserializationConfig getDeserializationConfig() {
789  2170 return _deserializationConfig;
790    }
791   
792    /**
793    * Method for getting current {@link DeserializationContext}.
794    *<p>
795    * Note that since instances are immutable, you can NOT change settings
796    * by accessing an instance and calling methods: this will simply create
797    * new instance of context object.
798    */
 
799  0 toggle public DeserializationContext getDeserializationContext() {
800  0 return _deserializationContext;
801    }
802   
803    /*
804    /**********************************************************
805    /* Configuration: ser/deser factory, provider access
806    /**********************************************************
807    */
808   
809    /**
810    * Method for setting specific {@link SerializerFactory} to use
811    * for constructing (bean) serializers.
812    */
 
813  2 toggle public ObjectMapper setSerializerFactory(SerializerFactory f) {
814  2 _serializerFactory = f;
815  2 return this;
816    }
817   
818    /**
819    * Method for getting current {@link SerializerFactory}.
820    *<p>
821    * Note that since instances are immutable, you can NOT change settings
822    * by accessing an instance and calling methods: this will simply create
823    * new instance of factory object.
824    */
 
825  0 toggle public SerializerFactory getSerializerFactory() {
826  0 return _serializerFactory;
827    }
828   
829    /**
830    * Method for setting specific {@link SerializerProvider} to use
831    * for handling caching of {@link JsonSerializer} instances.
832    */
 
833  4 toggle public ObjectMapper setSerializerProvider(DefaultSerializerProvider p) {
834  4 _serializerProvider = p;
835  4 return this;
836    }
837   
 
838  4 toggle public SerializerProvider getSerializerProvider() {
839  4 return _serializerProvider;
840    }
841   
842    /*
843    /**********************************************************
844    /* Configuration: mix-in annotations
845    /**********************************************************
846    */
847   
848    /**
849    * Method to use for defining mix-in annotations to use for augmenting
850    * annotations that processable (serializable / deserializable)
851    * classes have.
852    * Mixing in is done when introspecting class annotations and properties.
853    * Map passed contains keys that are target classes (ones to augment
854    * with new annotation overrides), and values that are source classes
855    * (have annotations to use for augmentation).
856    * Annotations from source classes (and their supertypes)
857    * will <b>override</b>
858    * annotations that target classes (and their super-types) have.
859    */
 
860  4 toggle public final void setMixInAnnotations(Map<Class<?>, Class<?>> sourceMixins)
861    {
862  4 _mixInAnnotations.clear();
863  4 if (sourceMixins != null && sourceMixins.size() > 0) {
864  4 for (Map.Entry<Class<?>,Class<?>> en : sourceMixins.entrySet()) {
865  8 _mixInAnnotations.put(new ClassKey(en.getKey()), en.getValue());
866    }
867    }
868    }
869   
870    /**
871    * Method to use for adding mix-in annotations to use for augmenting
872    * specified class or interface. All annotations from
873    * <code>mixinSource</code> are taken to override annotations
874    * that <code>target</code> (or its supertypes) has.
875    *
876    * @param target Class (or interface) whose annotations to effectively override
877    * @param mixinSource Class (or interface) whose annotations are to
878    * be "added" to target's annotations, overriding as necessary
879    */
 
880  66 toggle public final void addMixInAnnotations(Class<?> target, Class<?> mixinSource)
881    {
882  66 _mixInAnnotations.put(new ClassKey(target), mixinSource);
883    }
884   
 
885  0 toggle public final Class<?> findMixInClassFor(Class<?> cls) {
886  0 return (_mixInAnnotations == null) ? null : _mixInAnnotations.get(new ClassKey(cls));
887    }
888   
 
889  0 toggle public final int mixInCount() {
890  0 return (_mixInAnnotations == null) ? 0 : _mixInAnnotations.size();
891    }
892   
893    /*
894    /**********************************************************
895    /* Configuration, introspection
896    /**********************************************************
897    */
898   
899    /**
900    * Method for accessing currently configured visibility checker;
901    * object used for determining whether given property element
902    * (method, field, constructor) can be auto-detected or not.
903    */
 
904  8 toggle public VisibilityChecker<?> getVisibilityChecker() {
905  8 return _serializationConfig.getDefaultVisibilityChecker();
906    }
907   
908    /**
909    * Method for setting currently configured visibility checker;
910    * object used for determining whether given property element
911    * (method, field, constructor) can be auto-detected or not.
912    * This default checker is used if no per-class overrides
913    * are defined.
914    */
 
915  8 toggle public void setVisibilityChecker(VisibilityChecker<?> vc) {
916  8 _deserializationConfig = _deserializationConfig.with(vc);
917  8 _serializationConfig = _serializationConfig.with(vc);
918    }
919   
920    /**
921    * Convenience method that allows changing configuration for
922    * underlying {@link VisibilityChecker}s, to change details of what kinds of
923    * properties are auto-detected.
924    * Basically short cut for doing:
925    *<pre>
926    * mapper.setVisibilityChecker(
927    * mapper.getVisibilityChecker().withVisibility(forMethod, visibility)
928    * );
929    *</pre>
930    * one common use case would be to do:
931    *<pre>
932    * mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
933    *</pre>
934    * which would make all member fields serializable without further annotations,
935    * instead of just public fields (default setting).
936    *
937    * @param forMethod Type of property descriptor affected (field, getter/isGetter,
938    * setter, creator)
939    * @param visibility Minimum visibility to require for the property descriptors of type
940    *
941    * @return Modified mapper instance (that is, "this"), to allow chaining
942    * of configuration calls
943    */
 
944  6 toggle public ObjectMapper setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility)
945    {
946  6 _deserializationConfig = _deserializationConfig.withVisibility(forMethod, visibility);
947  6 _serializationConfig = _serializationConfig.withVisibility(forMethod, visibility);
948  6 return this;
949    }
950   
951    /**
952    * Method for accessing subtype resolver in use.
953    */
 
954  24 toggle public SubtypeResolver getSubtypeResolver() {
955  24 return _subtypeResolver;
956    }
957   
958    /**
959    * Method for setting custom subtype resolver to use.
960    */
 
961  0 toggle public ObjectMapper setSubtypeResolver(SubtypeResolver str) {
962  0 _subtypeResolver = str;
963  0 _deserializationConfig = _deserializationConfig.with(str);
964  0 _serializationConfig = _serializationConfig.with(str);
965  0 return this;
966    }
967   
968    /**
969    * Method for changing {@link AnnotationIntrospector} used by this
970    * mapper instance for both serialization and deserialization
971    */
 
972  4 toggle public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) {
973  4 _serializationConfig = _serializationConfig.with(ai);
974  4 _deserializationConfig = _deserializationConfig.with(ai);
975  4 return this;
976    }
977   
978    /**
979    * Method for changing {@link AnnotationIntrospector} instances used
980    * by this mapper instance for serialization and deserialization,
981    * specifying them separately so that different introspection can be
982    * used for different aspects
983    *
984    * @since 2.1
985    *
986    * @param serializerAI {@link AnnotationIntrospector} to use for configuring
987    * serialization
988    * @param deserializerAI {@link AnnotationIntrospector} to use for configuring
989    * deserialization
990    */
 
991  0 toggle public ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI,
992    AnnotationIntrospector deserializerAI) {
993  0 _serializationConfig = _serializationConfig.with(serializerAI);
994  0 _deserializationConfig = _deserializationConfig.with(deserializerAI);
995  0 return this;
996    }
997   
998    /**
999    * Method for setting custom property naming strategy to use.
1000    */
 
1001  26 toggle public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) {
1002  26 _serializationConfig = _serializationConfig.with(s);
1003  26 _deserializationConfig = _deserializationConfig.with(s);
1004  26 return this;
1005    }
1006   
1007    /**
1008    * Method for setting defalt POJO property inclusion strategy for serialization.
1009    */
 
1010  14 toggle public ObjectMapper setSerializationInclusion(JsonInclude.Include incl) {
1011  14 _serializationConfig = _serializationConfig.withSerializationInclusion(incl);
1012  14 return this;
1013    }
1014   
1015    /*
1016    /**********************************************************
1017    /* Type information configuration (1.5+)
1018    /**********************************************************
1019    */
1020   
1021    /**
1022    * Convenience method that is equivalent to calling
1023    *<pre>
1024    * enableObjectTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);
1025    *</pre>
1026    */
 
1027  30 toggle public ObjectMapper enableDefaultTyping() {
1028  30 return enableDefaultTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);
1029    }
1030   
1031    /**
1032    * Convenience method that is equivalent to calling
1033    *<pre>
1034    * enableObjectTyping(dti, JsonTypeInfo.As.WRAPPER_ARRAY);
1035    *</pre>
1036    */
 
1037  58 toggle public ObjectMapper enableDefaultTyping(DefaultTyping dti) {
1038  58 return enableDefaultTyping(dti, JsonTypeInfo.As.WRAPPER_ARRAY);
1039    }
1040   
1041    /**
1042    * Method for enabling automatic inclusion of type information, needed
1043    * for proper deserialization of polymorphic types (unless types
1044    * have been annotated with {@link com.fasterxml.jackson.annotation.JsonTypeInfo}).
1045    *
1046    * @param applicability Defines kinds of types for which additional type information
1047    * is added; see {@link DefaultTyping} for more information.
1048    */
 
1049  68 toggle public ObjectMapper enableDefaultTyping(DefaultTyping applicability, JsonTypeInfo.As includeAs)
1050    {
1051  68 TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(applicability);
1052    // we'll always use full class name, when using defaulting
1053  68 typer = typer.init(JsonTypeInfo.Id.CLASS, null);
1054  68 typer = typer.inclusion(includeAs);
1055  68 return setDefaultTyping(typer);
1056    }
1057   
1058    /**
1059    * Method for enabling automatic inclusion of type information -- needed
1060    * for proper deserialization of polymorphic types (unless types
1061    * have been annotated with {@link com.fasterxml.jackson.annotation.JsonTypeInfo}) --
1062    * using "As.PROPERTY" inclusion mechanism and specified property name
1063    * to use for inclusion (default being "@class" since default type information
1064    * always uses class name as type identifier)
1065    */
 
1066  6 toggle public ObjectMapper enableDefaultTypingAsProperty(DefaultTyping applicability, String propertyName)
1067    {
1068  6 TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(applicability);
1069    // we'll always use full class name, when using defaulting
1070  6 typer = typer.init(JsonTypeInfo.Id.CLASS, null);
1071  6 typer = typer.inclusion(JsonTypeInfo.As.PROPERTY);
1072  6 typer = typer.typeProperty(propertyName);
1073  6 return setDefaultTyping(typer);
1074    }
1075   
1076    /**
1077    * Method for disabling automatic inclusion of type information; if so, only
1078    * explicitly annotated types (ones with
1079    * {@link com.fasterxml.jackson.annotation.JsonTypeInfo}) will have
1080    * additional embedded type information.
1081    */
 
1082  2 toggle public ObjectMapper disableDefaultTyping() {
1083  2 return setDefaultTyping(null);
1084    }
1085   
1086    /**
1087    * Method for enabling automatic inclusion of type information, using
1088    * specified handler object for determining which types this affects,
1089    * as well as details of how information is embedded.
1090    *
1091    * @param typer Type information inclusion handler
1092    */
 
1093  80 toggle public ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer) {
1094  80 _deserializationConfig = _deserializationConfig.with(typer);
1095  80 _serializationConfig = _serializationConfig.with(typer);
1096  80 return this;
1097    }
1098   
1099    /**
1100    * Method for registering specified class as a subtype, so that
1101    * typename-based resolution can link supertypes to subtypes
1102    * (as an alternative to using annotations).
1103    * Type for given class is determined from appropriate annotation;
1104    * or if missing, default name (unqualified class name)
1105    */
 
1106  18 toggle public void registerSubtypes(Class<?>... classes) {
1107  18 getSubtypeResolver().registerSubtypes(classes);
1108    }
1109   
1110    /**
1111    * Method for registering specified class as a subtype, so that
1112    * typename-based resolution can link supertypes to subtypes
1113    * (as an alternative to using annotations).
1114    * Name may be provided as part of argument, but if not will
1115    * be based on annotations or use default name (unqualified
1116    * class name).
1117    */
 
1118  6 toggle public void registerSubtypes(NamedType... types) {
1119  6 getSubtypeResolver().registerSubtypes(types);
1120    }
1121   
1122    /*
1123    /**********************************************************
1124    /* Configuration, basic type handling
1125    /**********************************************************
1126    */
1127   
1128    /**
1129    * Accessor for getting currently configured {@link TypeFactory} instance.
1130    */
 
1131  10 toggle public TypeFactory getTypeFactory() {
1132  10 return _typeFactory;
1133    }
1134   
1135    /**
1136    * Method that can be used to override {@link TypeFactory} instance
1137    * used by this mapper.
1138    *<p>
1139    * Note: will also set {@link TypeFactory} that deserialization and
1140    * serialization config objects use.
1141    */
 
1142  10 toggle public ObjectMapper setTypeFactory(TypeFactory f)
1143    {
1144  10 _typeFactory = f;
1145  10 _deserializationConfig = _deserializationConfig.with(f);
1146  10 _serializationConfig = _serializationConfig.with(f);
1147  10 return this;
1148    }
1149   
1150    /**
1151    * Convenience method for constructing {@link JavaType} out of given
1152    * type (typically <code>java.lang.Class</code>), but without explicit
1153    * context.
1154    */
 
1155  46 toggle public JavaType constructType(Type t) {
1156  46 return _typeFactory.constructType(t);
1157    }
1158   
1159    /*
1160    /**********************************************************
1161    /* Configuration, deserialization
1162    /**********************************************************
1163    */
1164   
1165    /**
1166    * Method for specifying {@link JsonNodeFactory} to use for
1167    * constructing root level tree nodes (via method
1168    * {@link #createObjectNode}
1169    */
 
1170  2 toggle public ObjectMapper setNodeFactory(JsonNodeFactory f) {
1171  2 _deserializationConfig = _deserializationConfig.with(f);
1172  2 return this;
1173    }
1174   
1175    /**
1176    * Method for adding specified {@link DeserializationProblemHandler}
1177    * to be used for handling specific problems during deserialization.
1178    */
 
1179  2 toggle public ObjectMapper addHandler(DeserializationProblemHandler h) {
1180  2 _deserializationConfig = _deserializationConfig.withHandler(h);
1181  2 return this;
1182    }
1183   
1184    /**
1185    * Method for removing all registered {@link DeserializationProblemHandler}s
1186    * instances from this mapper.
1187    */
 
1188  4 toggle public ObjectMapper clearProblemHandlers() {
1189  4 _deserializationConfig = _deserializationConfig.withNoProblemHandlers();
1190  4 return this;
1191    }
1192   
1193   
1194    /*
1195    /**********************************************************
1196    /* Configuration, serialization
1197    /**********************************************************
1198    */
1199   
1200    /**
1201    * Convenience method that is equivalent to:
1202    *<pre>
1203    * mapper.setFilters(mapper.getSerializationConfig().withFilters(filterProvider));
1204    *</pre>
1205    *<p>
1206    * Note that usually it is better to use method {@link #writer(FilterProvider)};
1207    * however, sometimes
1208    * this method is more convenient. For example, some frameworks only allow configuring
1209    * of ObjectMapper instances and not ObjectWriters.
1210    */
 
1211  6 toggle public void setFilters(FilterProvider filterProvider) {
1212  6 _serializationConfig = _serializationConfig.withFilters(filterProvider);
1213    }
1214   
1215    /**
1216    * Method that will configure default {@link Base64Variant} that
1217    * <code>byte[]</code> serializers and deserializers will use.
1218    *
1219    * @param v Base64 variant to use
1220    *
1221    * @return This mapper, for convenience to allow chaining
1222    *
1223    * @since 2.1
1224    */
 
1225  0 toggle public ObjectMapper setBase64Variant(Base64Variant v) {
1226  0 _serializationConfig = _serializationConfig.with(v);
1227  0 _deserializationConfig = _deserializationConfig.with(v);
1228  0 return this;
1229    }
1230   
1231    /*
1232    /**********************************************************
1233    /* Configuration, other
1234    /**********************************************************
1235    */
1236   
1237    /**
1238    * Method that can be used to get hold of {@link JsonFactory} that this
1239    * mapper uses if it needs to construct {@link JsonParser}s
1240    * and/or {@link JsonGenerator}s.
1241    *
1242    * @return {@link JsonFactory} that this mapper uses when it needs to
1243    * construct Json parser and generators
1244    */
 
1245  51 toggle @Override
1246  51 public JsonFactory getFactory() { return _jsonFactory; }
1247   
1248    /**
1249    * @deprecated Since 2.1: Use {@link #getFactory} instead
1250    */
 
1251  0 toggle @Deprecated
1252    @Override
1253  0 public JsonFactory getJsonFactory() { return _jsonFactory; }
1254   
1255    /**
1256    * Method for configuring the default {@link DateFormat} to use when serializing time
1257    * values as Strings, and deserializing from JSON Strings.
1258    * This is preferably to directly modifying {@link SerializationConfig} and
1259    * {@link DeserializationConfig} instances.
1260    * If you need per-request configuration, use {@link #writer(DateFormat)} to
1261    * create properly configured {@link ObjectWriter} and use that; this because
1262    * {@link ObjectWriter}s are thread-safe whereas ObjectMapper itself is only
1263    * thread-safe when configuring methods (such as this one) are NOT called.
1264    */
 
1265  8 toggle public ObjectMapper setDateFormat(DateFormat dateFormat)
1266    {
1267  8 _deserializationConfig = _deserializationConfig.with(dateFormat);
1268  8 _serializationConfig = _serializationConfig.with(dateFormat);
1269  8 return this;
1270    }
1271   
1272    /**
1273    * Method for configuring {@link HandlerInstantiator} to use for creating
1274    * instances of handlers (such as serializers, deserializers, type and type
1275    * id resolvers), given a class.
1276    *
1277    * @param hi Instantiator to use; if null, use the default implementation
1278    */
 
1279  9 toggle public Object setHandlerInstantiator(HandlerInstantiator hi)
1280    {
1281  9 _deserializationConfig = _deserializationConfig.with(hi);
1282  9 _serializationConfig = _serializationConfig.with(hi);
1283  9 return this;
1284    }
1285   
1286    /**
1287    * Method for configuring {@link InjectableValues} which used to find
1288    * values to inject.
1289    */
 
1290  10 toggle public ObjectMapper setInjectableValues(InjectableValues injectableValues) {
1291  10 _injectableValues = injectableValues;
1292  10 return this;
1293    }
1294   
1295    /**
1296    * Method for overriding default locale to use for formatting.
1297    * Default value used is {@link Locale#getDefault()}.
1298    */
 
1299  0 toggle public ObjectMapper setLocale(Locale l) {
1300  0 _deserializationConfig = _deserializationConfig.with(l);
1301  0 _serializationConfig = _serializationConfig.with(l);
1302  0 return this;
1303    }
1304   
1305    /**
1306    * Method for overriding default TimeZone to use for formatting.
1307    * Default value used is {@link TimeZone#getDefault()}.
1308    */
 
1309  2 toggle public ObjectMapper setTimeZone(TimeZone tz) {
1310  2 _deserializationConfig = _deserializationConfig.with(tz);
1311  2 _serializationConfig = _serializationConfig.with(tz);
1312  2 return this;
1313    }
1314   
1315    /*
1316    /**********************************************************
1317    /* Configuration, simple features
1318    /**********************************************************
1319    */
1320   
1321    /**
1322    * Method for changing state of an on/off mapper feature for
1323    * this mapper instance.
1324    */
 
1325  56 toggle public ObjectMapper configure(MapperFeature f, boolean state) {
1326  56 _serializationConfig = state ?
1327    _serializationConfig.with(f) : _serializationConfig.without(f);
1328  56 _deserializationConfig = state ?
1329    _deserializationConfig.with(f) : _deserializationConfig.without(f);
1330  56 return this;
1331    }
1332   
1333    /**
1334    * Method for changing state of an on/off serialization feature for
1335    * this object mapper.
1336    */
 
1337  52 toggle public ObjectMapper configure(SerializationFeature f, boolean state) {
1338  52 _serializationConfig = state ?
1339    _serializationConfig.with(f) : _serializationConfig.without(f);
1340  52 return this;
1341    }
1342   
1343    /**
1344    * Method for changing state of an on/off deserialization feature for
1345    * this object mapper.
1346    */
 
1347  32 toggle public ObjectMapper configure(DeserializationFeature f, boolean state) {
1348  32 _deserializationConfig = state ?
1349    _deserializationConfig.with(f) : _deserializationConfig.without(f);
1350  32 return this;
1351    }
1352   
1353    /**
1354    * Method for changing state of an on/off {@link JsonParser} feature for
1355    * {@link JsonFactory} instance this object mapper uses.
1356    *<p>
1357    * This is method is basically a shortcut method for calling
1358    * {@link JsonFactory#enable} on the shared
1359    * {@link JsonFactory} this mapper uses (which is accessible
1360    * using {@link #getJsonFactory}).
1361    */
 
1362  0 toggle public ObjectMapper configure(JsonParser.Feature f, boolean state) {
1363  0 _jsonFactory.configure(f, state);
1364  0 return this;
1365    }
1366   
1367    /**
1368    * Method for changing state of an on/off {@link JsonGenerator} feature for
1369    * {@link JsonFactory} instance this object mapper uses.
1370    *<p>
1371    * This is method is basically a shortcut method for calling
1372    * {@link JsonFactory#enable} on the shared
1373    * {@link JsonFactory} this mapper uses (which is accessible
1374    * using {@link #getJsonFactory}).
1375    */
 
1376  2 toggle public ObjectMapper configure(JsonGenerator.Feature f, boolean state) {
1377  2 _jsonFactory.configure(f, state);
1378  2 return this;
1379    }
1380   
1381    /**
1382    * Method for enabling specified {@link MapperConfig} features.
1383    * Modifies and returns this instance; no new object is created.
1384    */
 
1385  6 toggle public ObjectMapper enable(MapperFeature... f) {
1386  6 _deserializationConfig = _deserializationConfig.with(f);
1387  6 _serializationConfig = _serializationConfig.with(f);
1388  6 return this;
1389    }
1390   
1391    /**
1392    * Method for enabling specified {@link DeserializationConfig} features.
1393    * Modifies and returns this instance; no new object is created.
1394    */
 
1395  16 toggle public ObjectMapper disable(MapperFeature... f) {
1396  16 _deserializationConfig = _deserializationConfig.without(f);
1397  16 _serializationConfig = _serializationConfig.without(f);
1398  16 return this;
1399    }
1400   
1401    /**
1402    * Method for enabling specified {@link DeserializationConfig} features.
1403    * Modifies and returns this instance; no new object is created.
1404    */
 
1405  16 toggle public ObjectMapper enable(DeserializationFeature feature) {
1406  16 _deserializationConfig = _deserializationConfig.with(feature);
1407  16 return this;
1408    }
1409   
1410    /**
1411    * Method for enabling specified {@link DeserializationConfig} features.
1412    * Modifies and returns this instance; no new object is created.
1413    */
 
1414  0 toggle public ObjectMapper enable(DeserializationFeature first,
1415    DeserializationFeature... f) {
1416  0 _deserializationConfig = _deserializationConfig.with(first, f);
1417  0 return this;
1418    }
1419   
1420    /**
1421    * Method for enabling specified {@link DeserializationConfig} features.
1422    * Modifies and returns this instance; no new object is created.
1423    */
 
1424  8 toggle public ObjectMapper disable(DeserializationFeature feature) {
1425  8 _deserializationConfig = _deserializationConfig.without(feature);
1426  8 return this;
1427    }
1428   
1429    /**
1430    * Method for enabling specified {@link DeserializationConfig} features.
1431    * Modifies and returns this instance; no new object is created.
1432    */
 
1433  0 toggle public ObjectMapper disable(DeserializationFeature first,
1434    DeserializationFeature... f) {
1435  0 _deserializationConfig = _deserializationConfig.without(first, f);
1436  0 return this;
1437    }
1438   
1439    /**
1440    * Method for enabling specified {@link DeserializationConfig} feature.
1441    * Modifies and returns this instance; no new object is created.
1442    */
 
1443  24 toggle public ObjectMapper enable(SerializationFeature f) {
1444  24 _serializationConfig = _serializationConfig.with(f);
1445  24 return this;
1446    }
1447   
1448    /**
1449    * Method for enabling specified {@link DeserializationConfig} features.
1450    * Modifies and returns this instance; no new object is created.
1451    */
 
1452  0 toggle public ObjectMapper enable(SerializationFeature first,
1453    SerializationFeature... f) {
1454  0 _serializationConfig = _serializationConfig.with(first, f);
1455  0 return this;
1456    }
1457   
1458    /**
1459    * Method for enabling specified {@link DeserializationConfig} features.
1460    * Modifies and returns this instance; no new object is created.
1461    */
 
1462  8 toggle public ObjectMapper disable(SerializationFeature f) {
1463  8 _serializationConfig = _serializationConfig.without(f);
1464  8 return this;
1465    }
1466   
1467    /**
1468    * Method for enabling specified {@link DeserializationConfig} features.
1469    * Modifies and returns this instance; no new object is created.
1470    */
 
1471  0 toggle public ObjectMapper disable(SerializationFeature first,
1472    SerializationFeature... f) {
1473  0 _serializationConfig = _serializationConfig.without(first, f);
1474  0 return this;
1475    }
1476   
1477    /**
1478    * Method for checking whether given Mapper
1479    * feature is enabled.
1480    */
 
1481  22 toggle public boolean isEnabled(MapperFeature f) {
1482    // ok to use either one, should be kept in sync
1483  22 return _serializationConfig.isEnabled(f);
1484    }
1485   
1486    /**
1487    * Method for checking whether given serialization-specific
1488    * feature is enabled.
1489    */
 
1490  10 toggle public boolean isEnabled(SerializationFeature f) {
1491  10 return _serializationConfig.isEnabled(f);
1492    }
1493   
1494    /**
1495    * Method for checking whether given deserialization-specific
1496    * feature is enabled.
1497    */
 
1498  20 toggle public boolean isEnabled(DeserializationFeature f) {
1499  20 return _deserializationConfig.isEnabled(f);
1500    }
1501   
1502    /**
1503    * Convenience method, equivalent to:
1504    *<pre>
1505    * getJsonFactory().isEnabled(f);
1506    *</pre>
1507    */
 
1508  0 toggle public boolean isEnabled(JsonFactory.Feature f) {
1509  0 return _jsonFactory.isEnabled(f);
1510    }
1511   
1512    /**
1513    * Convenience method, equivalent to:
1514    *<pre>
1515    * getJsonFactory().isEnabled(f);
1516    *</pre>
1517    */
 
1518  0 toggle public boolean isEnabled(JsonParser.Feature f) {
1519  0 return _jsonFactory.isEnabled(f);
1520    }
1521   
1522    /**
1523    * Convenience method, equivalent to:
1524    *<pre>
1525    * getJsonFactory().isEnabled(f);
1526    *</pre>
1527    */
 
1528  0 toggle public boolean isEnabled(JsonGenerator.Feature f) {
1529  0 return _jsonFactory.isEnabled(f);
1530    }
1531   
1532    /**
1533    * Method that can be used to get hold of {@link JsonNodeFactory}
1534    * that this mapper will use when directly constructing
1535    * root {@link JsonNode} instances for Trees.
1536    *<p>
1537    * Note: this is just a shortcut for calling
1538    *<pre>
1539    * getDeserializationConfig().getNodeFactory()
1540    *</pre>
1541    */
 
1542  18 toggle public JsonNodeFactory getNodeFactory() {
1543  18 return _deserializationConfig.getNodeFactory();
1544    }
1545   
1546    /*
1547    /**********************************************************
1548    /* Public API (from ObjectCodec): deserialization
1549    /* (mapping from JSON to Java types);
1550    /* main methods
1551    /**********************************************************
1552    */
1553   
1554    /**
1555    * Method to deserialize JSON content into a non-container
1556    * type (it can be an array type, however): typically a bean, array
1557    * or a wrapper type (like {@link java.lang.Boolean}).
1558    *<p>
1559    * Note: this method should NOT be used if the result type is a
1560    * container ({@link java.util.Collection} or {@link java.util.Map}.
1561    * The reason is that due to type erasure, key and value types
1562    * can not be introspected when using this method.
1563    */
 
1564  262 toggle @Override
1565    @SuppressWarnings("unchecked")
1566    public <T> T readValue(JsonParser jp, Class<T> valueType)
1567    throws IOException, JsonParseException, JsonMappingException
1568    {
1569  262 return (T) _readValue(getDeserializationConfig(), jp, _typeFactory.constructType(valueType));
1570    }
1571   
1572    /**
1573    * Method to deserialize JSON content into a Java type, reference
1574    * to which is passed as argument. Type is passed using so-called
1575    * "super type token" (see )
1576    * and specifically needs to be used if the root type is a
1577    * parameterized (generic) container type.
1578    */
 
1579  0 toggle @Override
1580    @SuppressWarnings("unchecked")
1581    public <T> T readValue(JsonParser jp, TypeReference<?> valueTypeRef)
1582    throws IOException, JsonParseException, JsonMappingException
1583    {
1584  0 return (T) _readValue(getDeserializationConfig(), jp, _typeFactory.constructType(valueTypeRef));
1585    }
1586   
1587    /**
1588    * Method to deserialize JSON content into a Java type, reference
1589    * to which is passed as argument. Type is passed using
1590    * Jackson specific type; instance of which can be constructed using
1591    * {@link TypeFactory}.
1592    */
 
1593  0 toggle @Override
1594    @SuppressWarnings("unchecked")
1595    public final <T> T readValue(JsonParser jp, ResolvedType valueType)
1596    throws IOException, JsonParseException, JsonMappingException
1597    {
1598  0 return (T) _readValue(getDeserializationConfig(), jp, (JavaType) valueType);
1599    }
1600   
1601    /**
1602    * Type-safe overloaded method, basically alias for {@link #readValue(JsonParser, ResolvedType)}.
1603    */
 
1604  0 toggle @SuppressWarnings("unchecked")
1605    public <T> T readValue(JsonParser jp, JavaType valueType)
1606    throws IOException, JsonParseException, JsonMappingException
1607    {
1608  0 return (T) _readValue(getDeserializationConfig(), jp, valueType);
1609    }
1610   
1611    /**
1612    * Method to deserialize JSON content as tree expressed
1613    * using set of {@link JsonNode} instances. Returns
1614    * root of the resulting tree (where root can consist
1615    * of just a single node if the current event is a
1616    * value event, not container).
1617    */
 
1618  24 toggle @Override
1619    public <T extends TreeNode> T readTree(JsonParser jp)
1620    throws IOException, JsonProcessingException
1621    {
1622    /* 02-Mar-2009, tatu: One twist; deserialization provider
1623    * will map JSON null straight into Java null. But what
1624    * we want to return is the "null node" instead.
1625    */
1626    /* 05-Aug-2011, tatu: Also, must check for EOF here before
1627    * calling readValue(), since that'll choke on it otherwise
1628    */
1629  24 DeserializationConfig cfg = getDeserializationConfig();
1630  24 JsonToken t = jp.getCurrentToken();
1631  24 if (t == null) {
1632  20 t = jp.nextToken();
1633  20 if (t == null) {
1634  4 return null;
1635    }
1636    }
1637  20 JsonNode n = (JsonNode) _readValue(cfg, jp, JSON_NODE_TYPE);
1638  20 if (n == null) {
1639  0 n = getNodeFactory().nullNode();
1640    }
1641  20 @SuppressWarnings("unchecked")
1642    T result = (T) n;
1643  20 return result;
1644    }
1645   
1646    /**
1647    * Method for reading sequence of Objects from parser stream.
1648    * Sequence can be either root-level "unwrapped" sequence (without surrounding
1649    * JSON array), or a sequence contained in a JSON Array.
1650    * In either case {@link JsonParser} must point to the first token of
1651    * the first element, OR not point to any token (in which case it is advanced
1652    * to the next token). This means, specifically, that for wrapped sequences,
1653    * parser MUST NOT point to the surrounding <code>START_ARRAY</code> but rather
1654    * to the token following it.
1655    *<p>
1656    * Note that {@link ObjectReader} has more complete set of variants.
1657    */
 
1658  0 toggle @Override
1659    public <T> MappingIterator<T> readValues(JsonParser jp, ResolvedType valueType)
1660    throws IOException, JsonProcessingException
1661    {
1662  0 return readValues(jp, (JavaType) valueType);
1663    }
1664   
1665    /**
1666    * Type-safe overloaded method, basically alias for {@link #readValues(JsonParser, ResolvedType)}.
1667    */
 
1668  4 toggle public <T> MappingIterator<T> readValues(JsonParser jp, JavaType valueType)
1669    throws IOException, JsonProcessingException
1670    {
1671  4 DeserializationConfig config = getDeserializationConfig();
1672  4 DeserializationContext ctxt = createDeserializationContext(jp, config);
1673  4 JsonDeserializer<?> deser = _findRootDeserializer(ctxt, valueType);
1674    // false -> do NOT close JsonParser (since caller passed it)
1675  4 return new MappingIterator<T>(valueType, jp, ctxt, deser,
1676    false, null);
1677    }
1678   
1679    /**
1680    * Type-safe overloaded method, basically alias for {@link #readValues(JsonParser, ResolvedType)}.
1681    */
 
1682  4 toggle @Override
1683    public <T> MappingIterator<T> readValues(JsonParser jp, Class<T> valueType)
1684    throws IOException, JsonProcessingException
1685    {
1686  4 return readValues(jp, _typeFactory.constructType(valueType));
1687    }
1688   
1689    /**
1690    * Method for reading sequence of Objects from parser stream.
1691    */
 
1692  0 toggle @Override
1693    public <T> MappingIterator<T> readValues(JsonParser jp, TypeReference<?> valueTypeRef)
1694    throws IOException, JsonProcessingException
1695    {
1696  0 return readValues(jp, _typeFactory.constructType(valueTypeRef));
1697    }
1698   
1699    /*
1700    /**********************************************************
1701    /* Public API not included in ObjectCodec: deserialization
1702    /* (mapping from JSON to Java types)
1703    /**********************************************************
1704    */
1705   
1706    /**
1707    * Method to deserialize JSON content as tree expressed
1708    * using set of {@link JsonNode} instances.
1709    * Returns root of the resulting tree (where root can consist
1710    * of just a single node if the current event is a
1711    * value event, not container).
1712    *
1713    * @param in Input stream used to read JSON content
1714    * for building the JSON tree.
1715    */
 
1716  2 toggle public JsonNode readTree(InputStream in)
1717    throws IOException, JsonProcessingException
1718    {
1719  2 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(in), JSON_NODE_TYPE);
1720  2 return (n == null) ? NullNode.instance : n;
1721    }
1722   
1723    /**
1724    * Method to deserialize JSON content as tree expressed
1725    * using set of {@link JsonNode} instances.
1726    * Returns root of the resulting tree (where root can consist
1727    * of just a single node if the current event is a
1728    * value event, not container).
1729    *
1730    * @param r Reader used to read JSON content
1731    * for building the JSON tree.
1732    */
 
1733  6 toggle public JsonNode readTree(Reader r)
1734    throws IOException, JsonProcessingException
1735    {
1736  6 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(r), JSON_NODE_TYPE);
1737  6 return (n == null) ? NullNode.instance : n;
1738    }
1739   
1740    /**
1741    * Method to deserialize JSON content as tree expressed using set of {@link JsonNode} instances.
1742    * Returns root of the resulting tree (where root can consist of just a single node if the current
1743    * event is a value event, not container).
1744    *
1745    * @param content JSON content to parse to build the JSON tree.
1746    */
 
1747  54 toggle public JsonNode readTree(String content)
1748    throws IOException, JsonProcessingException
1749    {
1750  54 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(content), JSON_NODE_TYPE);
1751  54 return (n == null) ? NullNode.instance : n;
1752    }
1753   
1754    /**
1755    * Method to deserialize JSON content as tree expressed using set of {@link JsonNode} instances.
1756    * Returns root of the resulting tree (where root can consist of just a single node if the current
1757    * event is a value event, not container).
1758    *
1759    * @param content JSON content to parse to build the JSON tree.
1760    */
 
1761  0 toggle public JsonNode readTree(byte[] content)
1762    throws IOException, JsonProcessingException
1763    {
1764  0 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(content), JSON_NODE_TYPE);
1765  0 return (n == null) ? NullNode.instance : n;
1766    }
1767   
1768    /**
1769    * Method to deserialize JSON content as tree expressed using set of {@link JsonNode} instances.
1770    * Returns root of the resulting tree (where root can consist of just a single node if the current
1771    * event is a value event, not container).
1772    *
1773    * @param file File of which contents to parse as JSON for building a tree instance
1774    */
 
1775  0 toggle public JsonNode readTree(File file)
1776    throws IOException, JsonProcessingException
1777    {
1778  0 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(file), JSON_NODE_TYPE);
1779  0 return (n == null) ? NullNode.instance : n;
1780    }
1781   
1782    /**
1783    * Method to deserialize JSON content as tree expressed using set of {@link JsonNode} instances.
1784    * Returns root of the resulting tree (where root can consist of just a single node if the current
1785    * event is a value event, not container).
1786    *
1787    * @param source URL to use for fetching contents to parse as JSON for building a tree instance
1788    */
 
1789  0 toggle public JsonNode readTree(URL source)
1790    throws IOException, JsonProcessingException
1791    {
1792  0 JsonNode n = (JsonNode) _readMapAndClose(_jsonFactory.createParser(source), JSON_NODE_TYPE);
1793  0 return (n == null) ? NullNode.instance : n;
1794    }
1795   
1796    /*
1797    /**********************************************************
1798    /* Public API (from ObjectCodec): serialization
1799    /* (mapping from Java types to Json)
1800    /**********************************************************
1801    */
1802   
1803    /**
1804    * Method that can be used to serialize any Java value as
1805    * JSON output, using provided {@link JsonGenerator}.
1806    */
 
1807  23 toggle @Override
1808    public void writeValue(JsonGenerator jgen, Object value)
1809    throws IOException, JsonGenerationException, JsonMappingException
1810    {
1811  23 SerializationConfig config = getSerializationConfig();
1812    // 10-Aug-2012, tatu: as per [Issue#12], must handle indentation:
1813  23 if (config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
1814  2 jgen.useDefaultPrettyPrinter();
1815    }
1816  23 if (config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
1817  0 _writeCloseableValue(jgen, value, config);
1818    } else {
1819  23 _serializerProvider(config).serializeValue(jgen, value);
1820  19 if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
1821  17 jgen.flush();
1822    }
1823    }
1824    }
1825   
1826    /**
1827    * Method to serialize given JSON Tree, using generator
1828    * provided.
1829    */
 
1830  8 toggle public void writeTree(JsonGenerator jgen, JsonNode rootNode)
1831    throws IOException, JsonProcessingException
1832    {
1833  8 SerializationConfig config = getSerializationConfig();
1834  8 _serializerProvider(config).serializeValue(jgen, rootNode);
1835  8 if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
1836  8 jgen.flush();
1837    }
1838    }
1839   
1840    /*
1841    /**********************************************************
1842    /* Public API (from ObjectCodec): Tree Model support
1843    /**********************************************************
1844    */
1845   
1846    /**
1847    *<p>
1848    * Note: return type is co-variant, as basic ObjectCodec
1849    * abstraction can not refer to concrete node types (as it's
1850    * part of core package, whereas impls are part of mapper
1851    * package)
1852    */
 
1853  34 toggle @Override
1854    public ObjectNode createObjectNode() {
1855  34 return _deserializationConfig.getNodeFactory().objectNode();
1856    }
1857   
1858    /**
1859    *<p>
1860    * Note: return type is co-variant, as basic ObjectCodec
1861    * abstraction can not refer to concrete node types (as it's
1862    * part of core package, whereas impls are part of mapper
1863    * package)
1864    */
 
1865  18 toggle @Override
1866    public ArrayNode createArrayNode() {
1867  18 return _deserializationConfig.getNodeFactory().arrayNode();
1868    }
1869   
1870    /**
1871    * Method for constructing a {@link JsonParser} out of JSON tree
1872    * representation.
1873    *
1874    * @param n Root node of the tree that resulting parser will read from
1875    */
 
1876  6 toggle @Override
1877    public JsonParser treeAsTokens(TreeNode n)
1878    {
1879  6 return new TreeTraversingParser((JsonNode) n, this);
1880    }
1881   
1882    /**
1883    * Convenience conversion method that will bind data given JSON tree
1884    * contains into specific value (usually bean) type.
1885    *<p>
1886    * Equivalent to:
1887    *<pre>
1888    * objectMapper.convertValue(n, valueClass);
1889    *</pre>
1890    */
 
1891  8 toggle @SuppressWarnings("unchecked")
1892    @Override
1893    public <T> T treeToValue(TreeNode n, Class<T> valueType)
1894    throws JsonProcessingException
1895    {
1896  8 try {
1897    // [Issue-11]: Simple cast when we just want to cast to, say, ObjectNode
1898    // ... one caveat; while everything is Object.class, let's not take shortcut
1899  8 if (valueType != Object.class && valueType.isAssignableFrom(n.getClass())) {
1900  2 return (T) n;
1901    }
1902  6 return readValue(treeAsTokens(n), valueType);
1903    } catch (JsonProcessingException e) {
1904  0 throw e;
1905    } catch (IOException e) { // should not occur, no real i/o...
1906  0 throw new IllegalArgumentException(e.getMessage(), e);
1907    }
1908    }
1909   
1910    /**
1911    * Reverse of {@link #treeToValue}; given a value (usually bean), will
1912    * construct equivalent JSON Tree representation. Functionally same
1913    * as if serializing value into JSON and parsing JSON as tree, but
1914    * more efficient.
1915    *
1916    * @param <T> Actual node type; usually either basic {@link JsonNode} or
1917    * {@link com.fasterxml.jackson.databind.node.ObjectNode}
1918    * @param fromValue Bean value to convert
1919    * @return Root node of the resulting JSON tree
1920    */
 
1921  0 toggle @SuppressWarnings("unchecked")
1922    public <T extends JsonNode> T valueToTree(Object fromValue)
1923    throws IllegalArgumentException
1924    {
1925  0 if (fromValue == null) return null;
1926  0 TokenBuffer buf = new TokenBuffer(this);
1927  0 JsonNode result;
1928  0 try {
1929  0 writeValue(buf, fromValue);
1930  0 JsonParser jp = buf.asParser();
1931  0 result = readTree(jp);
1932  0 jp.close();
1933    } catch (IOException e) { // should not occur, no real i/o...
1934  0 throw new IllegalArgumentException(e.getMessage(), e);
1935    }
1936  0 return (T) result;
1937    }
1938   
1939    /*
1940    /**********************************************************
1941    /* Extended Public API, accessors
1942    /**********************************************************
1943    */
1944   
1945    /**
1946    * Method that can be called to check whether mapper thinks
1947    * it could serialize an instance of given Class.
1948    * Check is done
1949    * by checking whether a serializer can be found for the type.
1950    *
1951    * @return True if mapper can find a serializer for instances of
1952    * given class (potentially serializable), false otherwise (not
1953    * serializable)
1954    */
 
1955  2 toggle public boolean canSerialize(Class<?> type) {
1956  2 return _serializerProvider(getSerializationConfig()).hasSerializerFor(type);
1957    }
1958   
1959    /**
1960    * Method that can be called to check whether mapper thinks
1961    * it could deserialize an Object of given type.
1962    * Check is done
1963    * by checking whether a deserializer can be found for the type.
1964    *
1965    * @return True if mapper can find a serializer for instances of
1966    * given class (potentially serializable), false otherwise (not
1967    * serializable)
1968    */
 
1969  2 toggle public boolean canDeserialize(JavaType type)
1970    {
1971  2 return createDeserializationContext(null,
1972    getDeserializationConfig()).hasValueDeserializerFor(type);
1973    }
1974   
1975    /*
1976    /**********************************************************
1977    /* Extended Public API, deserialization,
1978    /* convenience methods
1979    /**********************************************************
1980    */
1981   
 
1982  0 toggle @SuppressWarnings("unchecked")
1983    public <T> T readValue(File src, Class<T> valueType)
1984    throws IOException, JsonParseException, JsonMappingException
1985    {
1986    // !!! TODO
1987    // _setupClassLoaderForDeserialization(valueType);
1988  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
1989    }
1990   
 
1991  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
1992    public <T> T readValue(File src, TypeReference valueTypeRef)
1993    throws IOException, JsonParseException, JsonMappingException
1994    {
1995  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
1996    }
1997   
 
1998  0 toggle @SuppressWarnings("unchecked")
1999    public <T> T readValue(File src, JavaType valueType)
2000    throws IOException, JsonParseException, JsonMappingException
2001    {
2002  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
2003    }
2004   
 
2005  0 toggle @SuppressWarnings("unchecked")
2006    public <T> T readValue(URL src, Class<T> valueType)
2007    throws IOException, JsonParseException, JsonMappingException
2008    {
2009    // !!! TODO
2010    // _setupClassLoaderForDeserialization(valueType);
2011  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
2012    }
2013   
 
2014  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2015    public <T> T readValue(URL src, TypeReference valueTypeRef)
2016    throws IOException, JsonParseException, JsonMappingException
2017    {
2018  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
2019    }
2020   
 
2021  0 toggle @SuppressWarnings("unchecked")
2022    public <T> T readValue(URL src, JavaType valueType)
2023    throws IOException, JsonParseException, JsonMappingException
2024    {
2025  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
2026    }
2027   
 
2028  1367 toggle @SuppressWarnings("unchecked")
2029    public <T> T readValue(String content, Class<T> valueType)
2030    throws IOException, JsonParseException, JsonMappingException
2031    {
2032    // !!! TODO
2033    // _setupClassLoaderForDeserialization(valueType);
2034  1367 return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueType));
2035    }
2036   
 
2037  72 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2038    public <T> T readValue(String content, TypeReference valueTypeRef)
2039    throws IOException, JsonParseException, JsonMappingException
2040    {
2041  72 return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueTypeRef));
2042    }
2043   
 
2044  14 toggle @SuppressWarnings("unchecked")
2045    public <T> T readValue(String content, JavaType valueType)
2046    throws IOException, JsonParseException, JsonMappingException
2047    {
2048  14 return (T) _readMapAndClose(_jsonFactory.createParser(content), valueType);
2049    }
2050   
 
2051  136 toggle @SuppressWarnings("unchecked")
2052    public <T> T readValue(Reader src, Class<T> valueType)
2053    throws IOException, JsonParseException, JsonMappingException
2054    {
2055    // !!! TODO
2056    // _setupClassLoaderForDeserialization(valueType);
2057  136 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
2058    }
2059   
 
2060  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2061    public <T> T readValue(Reader src, TypeReference valueTypeRef)
2062    throws IOException, JsonParseException, JsonMappingException
2063    {
2064  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
2065    }
2066   
 
2067  0 toggle @SuppressWarnings("unchecked")
2068    public <T> T readValue(Reader src, JavaType valueType)
2069    throws IOException, JsonParseException, JsonMappingException
2070    {
2071  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
2072    }
2073   
 
2074  0 toggle @SuppressWarnings("unchecked")
2075    public <T> T readValue(InputStream src, Class<T> valueType)
2076    throws IOException, JsonParseException, JsonMappingException
2077    {
2078    // !!! TODO
2079    // _setupClassLoaderForDeserialization(valueType);
2080  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
2081    }
2082   
 
2083  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2084    public <T> T readValue(InputStream src, TypeReference valueTypeRef)
2085    throws IOException, JsonParseException, JsonMappingException
2086    {
2087  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
2088    }
2089   
 
2090  0 toggle @SuppressWarnings("unchecked")
2091    public <T> T readValue(InputStream src, JavaType valueType)
2092    throws IOException, JsonParseException, JsonMappingException
2093    {
2094  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
2095    }
2096   
 
2097  2 toggle @SuppressWarnings("unchecked")
2098    public <T> T readValue(byte[] src, Class<T> valueType)
2099    throws IOException, JsonParseException, JsonMappingException
2100    {
2101    // !!! TODO
2102    // _setupClassLoaderForDeserialization(valueType);
2103  2 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
2104    }
2105   
 
2106  0 toggle @SuppressWarnings("unchecked")
2107    public <T> T readValue(byte[] src, int offset, int len,
2108    Class<T> valueType)
2109    throws IOException, JsonParseException, JsonMappingException
2110    {
2111    // !!! TODO
2112    // _setupClassLoaderForDeserialization(valueType);
2113  0 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), _typeFactory.constructType(valueType));
2114    }
2115   
 
2116  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2117    public <T> T readValue(byte[] src, TypeReference valueTypeRef)
2118    throws IOException, JsonParseException, JsonMappingException
2119    {
2120  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
2121    }
2122   
 
2123  0 toggle @SuppressWarnings({ "unchecked", "rawtypes" })
2124    public <T> T readValue(byte[] src, int offset, int len,
2125    TypeReference valueTypeRef)
2126    throws IOException, JsonParseException, JsonMappingException
2127    {
2128  0 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), _typeFactory.constructType(valueTypeRef));
2129    }
2130   
 
2131  0 toggle @SuppressWarnings("unchecked")
2132    public <T> T readValue(byte[] src, JavaType valueType)
2133    throws IOException, JsonParseException, JsonMappingException
2134    {
2135  0 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
2136    }
2137   
 
2138  2 toggle @SuppressWarnings("unchecked")
2139    public <T> T readValue(byte[] src, int offset, int len,
2140    JavaType valueType)
2141    throws IOException, JsonParseException, JsonMappingException
2142    {
2143  2 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), valueType);
2144    }
2145   
2146    /*
2147    /**********************************************************
2148    /* Extended Public API: serialization
2149    /* (mapping from Java types to JSON)
2150    /**********************************************************
2151    */
2152   
2153    /**
2154    * Method that can be used to serialize any Java value as
2155    * JSON output, written to File provided.
2156    */
 
2157  0 toggle public void writeValue(File resultFile, Object value)
2158    throws IOException, JsonGenerationException, JsonMappingException
2159    {
2160  0 _configAndWriteValue(_jsonFactory.createGenerator(resultFile, JsonEncoding.UTF8), value);
2161    }
2162   
2163    /**
2164    * Method that can be used to serialize any Java value as
2165    * JSON output, using output stream provided (using encoding
2166    * {@link JsonEncoding#UTF8}).
2167    *<p>
2168    * Note: method does not close the underlying stream explicitly
2169    * here; however, {@link JsonFactory} this mapper uses may choose
2170    * to close the stream depending on its settings (by default,
2171    * it will try to close it when {@link JsonGenerator} we construct
2172    * is closed).
2173    */
 
2174  2 toggle public void writeValue(OutputStream out, Object value)
2175    throws IOException, JsonGenerationException, JsonMappingException
2176    {
2177  2 _configAndWriteValue(_jsonFactory.createGenerator(out, JsonEncoding.UTF8), value);
2178    }
2179   
2180    /**
2181    * Method that can be used to serialize any Java value as
2182    * JSON output, using Writer provided.
2183    *<p>
2184    * Note: method does not close the underlying stream explicitly
2185    * here; however, {@link JsonFactory} this mapper uses may choose
2186    * to close the stream depending on its settings (by default,
2187    * it will try to close it when {@link JsonGenerator} we construct
2188    * is closed).
2189    */
 
2190  52 toggle public void writeValue(Writer w, Object value)
2191    throws IOException, JsonGenerationException, JsonMappingException
2192    {
2193  52 _configAndWriteValue(_jsonFactory.createGenerator(w), value);
2194    }
2195   
2196    /**
2197    * Method that can be used to serialize any Java value as
2198    * a String. Functionally equivalent to calling
2199    * {@link #writeValue(Writer,Object)} with {@link java.io.StringWriter}
2200    * and constructing String, but more efficient.
2201    *<p>
2202    * Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it.
2203    */
 
2204  1097 toggle public String writeValueAsString(Object value)
2205    throws JsonProcessingException
2206    {
2207    // alas, we have to pull the recycler directly here...
2208  1097 SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler());
2209  1097 try {
2210  1097 _configAndWriteValue(_jsonFactory.createGenerator(sw), value);
2211    } catch (JsonProcessingException e) { // to support [JACKSON-758]
2212  20 throw e;
2213    } catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
2214  0 throw JsonMappingException.fromUnexpectedIOE(e);
2215    }
2216  1077 return sw.getAndClear();
2217    }
2218   
2219    /**
2220    * Method that can be used to serialize any Java value as
2221    * a byte array. Functionally equivalent to calling
2222    * {@link #writeValue(Writer,Object)} with {@link java.io.ByteArrayOutputStream}
2223    * and getting bytes, but more efficient.
2224    * Encoding used will be UTF-8.
2225    *<p>
2226    * Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it.
2227    */
 
2228  14 toggle public byte[] writeValueAsBytes(Object value)
2229    throws JsonProcessingException
2230    {
2231  14 ByteArrayBuilder bb = new ByteArrayBuilder(_jsonFactory._getBufferRecycler());
2232  14 try {
2233  14 _configAndWriteValue(_jsonFactory.createGenerator(bb, JsonEncoding.UTF8), value);
2234    } catch (JsonProcessingException e) { // to support [JACKSON-758]
2235  0 throw e;
2236    } catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
2237  0 throw JsonMappingException.fromUnexpectedIOE(e);
2238    }
2239  14 byte[] result = bb.toByteArray();
2240  14 bb.release();
2241  14 return result;
2242    }
2243   
2244    /*
2245    /**********************************************************
2246    /* Extended Public API: constructing ObjectWriters
2247    /* for more advanced configuration
2248    /**********************************************************
2249    */
2250   
2251    /**
2252    * Convenience method for constructing {@link ObjectWriter}
2253    * with default settings.
2254    */
 
2255  48 toggle public ObjectWriter writer() {
2256  48 return new ObjectWriter(this, getSerializationConfig());
2257    }
2258   
2259    /**
2260    * Factory method for constructing {@link ObjectWriter} with
2261    * specified feature enabled (compared to settings that this
2262    * mapper instance has).
2263    */
 
2264  4 toggle public ObjectWriter writer(SerializationFeature feature) {
2265  4 return new ObjectWriter(this, getSerializationConfig().with(feature));
2266    }
2267   
2268    /**
2269    * Factory method for constructing {@link ObjectWriter} with
2270    * specified features enabled (compared to settings that this
2271    * mapper instance has).
2272    */
 
2273  0 toggle public ObjectWriter writer(SerializationFeature first,
2274    SerializationFeature... other) {
2275  0 return new ObjectWriter(this, getSerializationConfig().with(first, other));
2276    }
2277   
2278    /**
2279    * Factory method for constructing {@link ObjectWriter} that will
2280    * serialize objects using specified {@link DateFormat}; or, if
2281    * null passed, using timestamp (64-bit number.
2282    */
 
2283  4 toggle public ObjectWriter writer(DateFormat df) {
2284  4 return new ObjectWriter(this,
2285    getSerializationConfig().with(df));
2286    }
2287   
2288    /**
2289    * Factory method for constructing {@link ObjectWriter} that will
2290    * serialize objects using specified JSON View (filter).
2291    */
 
2292  28 toggle public ObjectWriter writerWithView(Class<?> serializationView) {
2293  28 return new ObjectWriter(this, getSerializationConfig().withView(serializationView));
2294    }
2295   
2296    /**
2297    * Factory method for constructing {@link ObjectWriter} that will
2298    * serialize objects using specified root type, instead of actual
2299    * runtime type of value. Type must be a super-type of runtime
2300    * type.
2301    */
 
2302  20 toggle public ObjectWriter writerWithType(Class<?> rootType) {
2303  20 return new ObjectWriter(this, getSerializationConfig(),
2304    // 15-Mar-2013, tatu: Important! Indicate that static typing is needed:
2305  20 ((rootType == null) ? null :_typeFactory.constructType(rootType)),
2306    /*PrettyPrinter*/null);
2307    }
2308   
2309    /**
2310    * Factory method for constructing {@link ObjectWriter} that will
2311    * serialize objects using specified root type, instead of actual
2312    * runtime type of value. Type must be a super-type of runtime type.
2313    */
 
2314  8 toggle public ObjectWriter writerWithType(TypeReference<?> rootType) {
2315  8 return new ObjectWriter(this, getSerializationConfig(),
2316    // 15-Mar-2013, tatu: Important! Indicate that static typing is needed:
2317  8 ((rootType == null) ? null : _typeFactory.constructType(rootType)),
2318    /*PrettyPrinter*/null);
2319    }
2320   
2321    /**
2322    * Factory method for constructing {@link ObjectWriter} that will
2323    * serialize objects using specified root type, instead of actual
2324    * runtime type of value. Type must be a super-type of runtime type.
2325    */
 
2326  12 toggle public ObjectWriter writerWithType(JavaType rootType) {
2327  12 return new ObjectWriter(this, getSerializationConfig(), rootType, /*PrettyPrinter*/null);
2328    }
2329   
2330    /**
2331    * Factory method for constructing {@link ObjectWriter} that will
2332    * serialize objects using specified pretty printer for indentation
2333    * (or if null, no pretty printer)
2334    */
 
2335  0 toggle public ObjectWriter writer(PrettyPrinter pp) {
2336  0 if (pp == null) { // need to use a marker to indicate explicit disabling of pp
2337  0 pp = ObjectWriter.NULL_PRETTY_PRINTER;
2338    }
2339  0 return new ObjectWriter(this, getSerializationConfig(), /*root type*/ null, pp);
2340    }
2341   
2342    /**
2343    * Factory method for constructing {@link ObjectWriter} that will
2344    * serialize objects using the default pretty printer for indentation
2345    */
 
2346  2 toggle public ObjectWriter writerWithDefaultPrettyPrinter() {
2347  2 return new ObjectWriter(this, getSerializationConfig(),
2348    /*root type*/ null, _defaultPrettyPrinter());
2349    }
2350   
2351    /**
2352    * Factory method for constructing {@link ObjectWriter} that will
2353    * serialize objects using specified filter provider.
2354    */
 
2355  6 toggle public ObjectWriter writer(FilterProvider filterProvider) {
2356  6 return new ObjectWriter(this,
2357    getSerializationConfig().withFilters(filterProvider));
2358    }
2359   
2360    /**
2361    * Factory method for constructing {@link ObjectWriter} that will
2362    * pass specific schema object to {@link JsonGenerator} used for
2363    * writing content.
2364    *
2365    * @param schema Schema to pass to generator
2366    */
 
2367  3 toggle public ObjectWriter writer(FormatSchema schema) {
2368  3 _verifySchemaType(schema);
2369  3 return new ObjectWriter(this, getSerializationConfig(), schema);
2370    }
2371   
2372    /**
2373    * Factory method for constructing {@link ObjectWriter} that will
2374    * use specified Base64 encoding variant for Base64-encoded binary data.
2375    *
2376    * @since 2.1
2377    */
 
2378  8 toggle public ObjectWriter writer(Base64Variant defaultBase64) {
2379  8 return new ObjectWriter(this, getSerializationConfig().with(defaultBase64));
2380    }
2381   
2382    /*
2383    /**********************************************************
2384    /* Extended Public API: constructing ObjectReaders
2385    /* for more advanced configuration
2386    /**********************************************************
2387    */
2388   
2389    /**
2390    * Factory method for constructing {@link ObjectReader} with
2391    * default settings. Note that the resulting instance is NOT usable as is,
2392    * without defining expected value type.
2393    */
 
2394  12 toggle public ObjectReader reader() {
2395  12 return new ObjectReader(this, getDeserializationConfig())
2396    .with(_injectableValues);
2397    }
2398   
2399    /**
2400    * Factory method for constructing {@link ObjectReader} with
2401    * specified feature enabled (compared to settings that this
2402    * mapper instance has).
2403    * Note that the resulting instance is NOT usable as is,
2404    * without defining expected value type.
2405    */
 
2406  8 toggle public ObjectReader reader(DeserializationFeature feature) {
2407  8 return new ObjectReader(this, getDeserializationConfig().with(feature));
2408    }
2409   
2410    /**
2411    * Factory method for constructing {@link ObjectReader} with
2412    * specified features enabled (compared to settings that this
2413    * mapper instance has).
2414    * Note that the resulting instance is NOT usable as is,
2415    * without defining expected value type.
2416    */
 
2417  0 toggle public ObjectReader reader(DeserializationFeature first,
2418    DeserializationFeature... other) {
2419  0 return new ObjectReader(this, getDeserializationConfig().with(first, other));
2420    }
2421   
2422    /**
2423    * Factory method for constructing {@link ObjectReader} that will
2424    * update given Object (usually Bean, but can be a Collection or Map
2425    * as well, but NOT an array) with JSON data. Deserialization occurs
2426    * normally except that the root-level value in JSON is not used for
2427    * instantiating a new object; instead give updateable object is used
2428    * as root.
2429    * Runtime type of value object is used for locating deserializer,
2430    * unless overridden by other factory methods of {@link ObjectReader}
2431    */
 
2432  14 toggle public ObjectReader readerForUpdating(Object valueToUpdate)
2433    {
2434  14 JavaType t = _typeFactory.constructType(valueToUpdate.getClass());
2435  14 return new ObjectReader(this, getDeserializationConfig(), t, valueToUpdate,
2436    null, _injectableValues);
2437    }
2438   
2439    /**
2440    * Factory method for constructing {@link ObjectReader} that will
2441    * read or update instances of specified type
2442    */
 
2443  66 toggle public ObjectReader reader(JavaType type)
2444    {
2445  66 return new ObjectReader(this, getDeserializationConfig(), type, null,
2446    null, _injectableValues);
2447    }
2448   
2449    /**
2450    * Factory method for constructing {@link ObjectReader} that will
2451    * read or update instances of specified type
2452    */
 
2453  66 toggle public ObjectReader reader(Class<?> type)
2454    {
2455  66 return reader(_typeFactory.constructType(type));
2456    }
2457   
2458    /**
2459    * Factory method for constructing {@link ObjectReader} that will
2460    * read or update instances of specified type
2461    */
 
2462  0 toggle public ObjectReader reader(TypeReference<?> type)
2463    {
2464  0 return reader(_typeFactory.constructType(type));
2465    }
2466   
2467    /**
2468    * Factory method for constructing {@link ObjectReader} that will
2469    * use specified {@link JsonNodeFactory} for constructing JSON trees.
2470    */
 
2471  0 toggle public ObjectReader reader(JsonNodeFactory f)
2472    {
2473  0 return new ObjectReader(this, getDeserializationConfig()).with(f);
2474    }
2475   
2476    /**
2477    * Factory method for constructing {@link ObjectReader} that will
2478    * pass specific schema object to {@link JsonParser} used for
2479    * reading content.
2480    *
2481    * @param schema Schema to pass to parser
2482    */
 
2483  3 toggle public ObjectReader reader(FormatSchema schema) {
2484  3 _verifySchemaType(schema);
2485  3 return new ObjectReader(this, getDeserializationConfig(), null, null,
2486    schema, _injectableValues);
2487    }
2488   
2489    /**
2490    * Factory method for constructing {@link ObjectReader} that will
2491    * use specified injectable values.
2492    *
2493    * @param injectableValues Injectable values to use
2494    */
 
2495  0 toggle public ObjectReader reader(InjectableValues injectableValues) {
2496  0 return new ObjectReader(this, getDeserializationConfig(), null, null,
2497    null, injectableValues);
2498    }
2499   
2500    /**
2501    * Factory method for constructing {@link ObjectReader} that will
2502    * deserialize objects using specified JSON View (filter).
2503    */
 
2504  6 toggle public ObjectReader readerWithView(Class<?> view) {
2505  6 return new ObjectReader(this, getDeserializationConfig().withView(view));
2506    }
2507   
2508    /**
2509    * Factory method for constructing {@link ObjectReader} that will
2510    * use specified Base64 encoding variant for Base64-encoded binary data.
2511    *
2512    * @since 2.1
2513    */
 
2514  0 toggle public ObjectReader reader(Base64Variant defaultBase64) {
2515  0 return new ObjectReader(this, getDeserializationConfig().with(defaultBase64));
2516    }
2517   
2518    /*
2519    /**********************************************************
2520    /* Extended Public API: convenience type conversion
2521    /**********************************************************
2522    */
2523   
2524    /**
2525    * Convenience method for doing two-step conversion from given value, into
2526    * instance of given value type. This is functionality equivalent to first
2527    * serializing given value into JSON, then binding JSON data into value
2528    * of given type, but may be executed without fully serializing into
2529    * JSON. Same converters (serializers, deserializers) will be used as for
2530    * data binding, meaning same object mapper configuration works.
2531    *
2532    * @throws IllegalArgumentException If conversion fails due to incompatible type;
2533    * if so, root cause will contain underlying checked exception data binding
2534    * functionality threw
2535    */
 
2536  100 toggle @SuppressWarnings("unchecked")
2537    public <T> T convertValue(Object fromValue, Class<T> toValueType)
2538    throws IllegalArgumentException
2539    {
2540    // sanity check for null first:
2541  6 if (fromValue == null) return null;
2542  94 return (T) _convert(fromValue, _typeFactory.constructType(toValueType));
2543    }
2544   
 
2545  10 toggle @SuppressWarnings("unchecked")
2546    public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef)
2547    throws IllegalArgumentException
2548    {
2549  10 return (T) convertValue(fromValue, _typeFactory.constructType(toValueTypeRef));
2550    }
2551   
 
2552  10 toggle @SuppressWarnings("unchecked")
2553    public <T> T convertValue(Object fromValue, JavaType toValueType)
2554    throws IllegalArgumentException
2555    {
2556    // sanity check for null first:
2557  10 if (fromValue == null) return null;
2558  10 return (T) _convert(fromValue, toValueType);
2559    }
2560   
2561    /**
2562    * Actual conversion implementation: instead of using existing read
2563    * and write methods, much of code is inlined. Reason for this is
2564    * that we must avoid wrapping/unwrapping both for efficiency and
2565    * for correctness. If wrapping/unwrapping is actually desired,
2566    * caller must use explicit <code>writeValue</code> and
2567    * <code>readValue</code> methods.
2568    */
 
2569  104 toggle protected Object _convert(Object fromValue, JavaType toValueType)
2570    throws IllegalArgumentException
2571    {
2572    // also, as per [Issue-11], consider case for simple cast
2573    /* But with caveats: one is that while everything is Object.class, we don't
2574    * want to "optimize" that out; and the other is that we also do not want
2575    * to lose conversions of generic types.
2576    */
2577  104 Class<?> targetType = toValueType.getRawClass();
2578  104 if (targetType != Object.class
2579    && !toValueType.hasGenericTypes()
2580    && targetType.isAssignableFrom(fromValue.getClass())) {
2581  28 return fromValue;
2582    }
2583   
2584    /* Then use TokenBuffer, which is a JsonGenerator:
2585    * (see [JACKSON-175])
2586    */
2587  76 TokenBuffer buf = new TokenBuffer(this);
2588  76 try {
2589    // inlined 'writeValue' with minor changes:
2590    // first: disable wrapping when writing
2591  76 SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE);
2592    // no need to check for closing of TokenBuffer
2593  76 _serializerProvider(config).serializeValue(buf, fromValue);
2594   
2595    // then matching read, inlined 'readValue' with minor mods:
2596  74 final JsonParser jp = buf.asParser();
2597  74 Object result;
2598    // ok to pass in existing feature flags; unwrapping handled by mapper
2599  74 final DeserializationConfig deserConfig = getDeserializationConfig();
2600  74 JsonToken t = _initForReading(jp);
2601  74 if (t == JsonToken.VALUE_NULL) {
2602  0 DeserializationContext ctxt = createDeserializationContext(jp, deserConfig);
2603  0 result = _findRootDeserializer(ctxt, toValueType).getNullValue();
2604  74 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2605  0 result = null;
2606    } else { // pointing to event other than null
2607  74 DeserializationContext ctxt = createDeserializationContext(jp, deserConfig);
2608  74 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, toValueType);
2609    // note: no handling of unwarpping
2610  74 result = deser.deserialize(jp, ctxt);
2611    }
2612  70 jp.close();
2613  70 return result;
2614    } catch (IOException e) { // should not occur, no real i/o...
2615  6 throw new IllegalArgumentException(e.getMessage(), e);
2616    }
2617    }
2618   
2619    /*
2620    /**********************************************************
2621    /* Extended Public API: JSON Schema generation
2622    /**********************************************************
2623    */
2624   
2625    /**
2626    * Generate <a href="http://json-schema.org/">Json-schema</a>
2627    * instance for specified class.
2628    *
2629    * @param t The class to generate schema for
2630    * @return Constructed JSON schema.
2631    */
 
2632  14 toggle @SuppressWarnings("deprecation")
2633    public com.fasterxml.jackson.databind.jsonschema.JsonSchema generateJsonSchema(Class<?> t)
2634    throws JsonMappingException {
2635  14 return _serializerProvider(getSerializationConfig()).generateJsonSchema(t);
2636    }
2637   
2638    /**
2639    * Method for visiting type hierarchy for given type, using specified visitor.
2640    *<p>
2641    * This method can be used for things like
2642    * generating <a href="http://json-schema.org/">Json Schema</a>
2643    * instance for specified type.
2644    *
2645    * @param type Type to generate schema for (possibly with generic signature)
2646    *
2647    * @since 2.1
2648    */
 
2649  0 toggle public void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor)
2650    throws JsonMappingException
2651    {
2652  0 acceptJsonFormatVisitor(_typeFactory.constructType(type), visitor);
2653    }
2654   
2655    /**
2656    * Method for visiting type hierarchy for given type, using specified visitor.
2657    * Visitation uses <code>Serializer</code> hierarchy and related properties
2658    *<p>
2659    * This method can be used for things like
2660    * generating <a href="http://json-schema.org/">Json Schema</a>
2661    * instance for specified type.
2662    *
2663    * @param type Type to generate schema for (possibly with generic signature)
2664    *
2665    * @since 2.1
2666    */
 
2667  0 toggle public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor)
2668    throws JsonMappingException
2669    {
2670  0 if (type == null) {
2671  0 throw new IllegalArgumentException("type must be provided");
2672    }
2673  0 _serializerProvider(getSerializationConfig()).acceptJsonFormatVisitor(type, visitor);
2674    }
2675   
2676    /*
2677    /**********************************************************
2678    /* Internal methods for serialization, overridable
2679    /**********************************************************
2680    */
2681   
2682    /**
2683    * Overridable helper method used for constructing
2684    * {@link SerializerProvider} to use for serialization.
2685    */
 
2686  1288 toggle protected DefaultSerializerProvider _serializerProvider(SerializationConfig config) {
2687  1288 return _serializerProvider.createInstance(config, _serializerFactory);
2688    }
2689   
2690    /**
2691    * Helper method that should return default pretty-printer to
2692    * use for generators constructed by this mapper, when instructed
2693    * to use default pretty printer.
2694    */
 
2695  2 toggle protected PrettyPrinter _defaultPrettyPrinter() {
2696  2 return _defaultPrettyPrinter;
2697    }
2698   
2699    /**
2700    * Method called to configure the generator as necessary and then
2701    * call write functionality
2702    */
 
2703  1165 toggle protected final void _configAndWriteValue(JsonGenerator jgen, Object value)
2704    throws IOException, JsonGenerationException, JsonMappingException
2705    {
2706  1165 SerializationConfig cfg = getSerializationConfig();
2707    // [JACKSON-96]: allow enabling pretty printing for ObjectMapper directly
2708  1165 if (cfg.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
2709  8 jgen.useDefaultPrettyPrinter();
2710    }
2711    // [JACKSON-282]: consider Closeable
2712  1165 if (cfg.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
2713  2 _configAndWriteCloseable(jgen, value, cfg);
2714  2 return;
2715    }
2716  1163 boolean closed = false;
2717  1163 try {
2718  1163 _serializerProvider(cfg).serializeValue(jgen, value);
2719  1139 closed = true;
2720  1139 jgen.close();
2721    } finally {
2722    /* won't try to close twice; also, must catch exception (so it
2723    * will not mask exception that is pending)
2724    */
2725  1163 if (!closed) {
2726  24 try {
2727  24 jgen.close();
2728    } catch (IOException ioe) { }
2729    }
2730    }
2731    }
2732   
 
2733  0 toggle protected final void _configAndWriteValue(JsonGenerator jgen, Object value, Class<?> viewClass)
2734    throws IOException, JsonGenerationException, JsonMappingException
2735    {
2736  0 SerializationConfig cfg = getSerializationConfig().withView(viewClass);
2737  0 if (cfg.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
2738  0 jgen.useDefaultPrettyPrinter();
2739    }
2740    // [JACKSON-282]: consider Closeable
2741  0 if (cfg.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
2742  0 _configAndWriteCloseable(jgen, value, cfg);
2743  0 return;
2744    }
2745  0 boolean closed = false;
2746  0 try {
2747  0 _serializerProvider(cfg).serializeValue(jgen, value);
2748  0 closed = true;
2749  0 jgen.close();
2750    } finally {
2751  0 if (!closed) {
2752  0 try {
2753  0 jgen.close();
2754    } catch (IOException ioe) { }
2755    }
2756    }
2757    }
2758   
2759    /**
2760    * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
2761    * method is to be called right after serialization has been called
2762    */
 
2763  2 toggle private final void _configAndWriteCloseable(JsonGenerator jgen, Object value, SerializationConfig cfg)
2764    throws IOException, JsonGenerationException, JsonMappingException
2765    {
2766  2 Closeable toClose = (Closeable) value;
2767  2 try {
2768  2 _serializerProvider(cfg).serializeValue(jgen, value);
2769  2 JsonGenerator tmpJgen = jgen;
2770  2 jgen = null;
2771  2 tmpJgen.close();
2772  2 Closeable tmpToClose = toClose;
2773  2 toClose = null;
2774  2 tmpToClose.close();
2775    } finally {
2776    /* Need to close both generator and value, as long as they haven't yet
2777    * been closed
2778    */
2779  2 if (jgen != null) {
2780  0 try {
2781  0 jgen.close();
2782    } catch (IOException ioe) { }
2783    }
2784  2 if (toClose != null) {
2785  0 try {
2786  0 toClose.close();
2787    } catch (IOException ioe) { }
2788    }
2789    }
2790    }
2791   
2792    /**
2793    * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
2794    * method is to be called right after serialization has been called
2795    */
 
2796  0 toggle private final void _writeCloseableValue(JsonGenerator jgen, Object value, SerializationConfig cfg)
2797    throws IOException, JsonGenerationException, JsonMappingException
2798    {
2799  0 Closeable toClose = (Closeable) value;
2800  0 try {
2801  0 _serializerProvider(cfg).serializeValue(jgen, value);
2802  0 if (cfg.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
2803  0 jgen.flush();
2804    }
2805  0 Closeable tmpToClose = toClose;
2806  0 toClose = null;
2807  0 tmpToClose.close();
2808    } finally {
2809  0 if (toClose != null) {
2810  0 try {
2811  0 toClose.close();
2812    } catch (IOException ioe) { }
2813    }
2814    }
2815    }
2816   
2817    /*
2818    /**********************************************************
2819    /* Internal methods for deserialization, overridable
2820    /**********************************************************
2821    */
2822   
2823    /**
2824    * Internal helper method called to create an instance of {@link DeserializationContext}
2825    * for deserializing a single root value.
2826    * Can be overridden if a custom context is needed.
2827    */
 
2828  2011 toggle protected DefaultDeserializationContext createDeserializationContext(JsonParser jp,
2829    DeserializationConfig cfg)
2830    {
2831  2011 return _deserializationContext.createInstance(cfg,
2832    jp, _injectableValues);
2833    }
2834   
2835    /**
2836    * Actual implementation of value reading+binding operation.
2837    */
 
2838  282 toggle protected Object _readValue(DeserializationConfig cfg, JsonParser jp, JavaType valueType)
2839    throws IOException, JsonParseException, JsonMappingException
2840    {
2841    /* First: may need to read the next token, to initialize
2842    * state (either before first read from parser, or after
2843    * previous token has been cleared)
2844    */
2845  282 Object result;
2846  282 JsonToken t = _initForReading(jp);
2847  280 if (t == JsonToken.VALUE_NULL) {
2848    // [JACKSON-643]: Ask JsonDeserializer what 'null value' to use:
2849  4 DeserializationContext ctxt = createDeserializationContext(jp, cfg);
2850  4 result = _findRootDeserializer(ctxt, valueType).getNullValue();
2851  276 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2852  2 result = null;
2853    } else { // pointing to event other than null
2854  274 DeserializationContext ctxt = createDeserializationContext(jp, cfg);
2855  274 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
2856    // ok, let's get the value
2857  274 if (cfg.useRootWrapping()) {
2858  0 result = _unwrapAndDeserialize(jp, ctxt, cfg, valueType, deser);
2859    } else {
2860  274 result = deser.deserialize(jp, ctxt);
2861    }
2862    }
2863    // Need to consume the token too
2864  278 jp.clearCurrentToken();
2865  278 return result;
2866    }
2867   
 
2868  1655 toggle protected Object _readMapAndClose(JsonParser jp, JavaType valueType)
2869    throws IOException, JsonParseException, JsonMappingException
2870    {
2871  1655 try {
2872  1655 Object result;
2873  1655 JsonToken t = _initForReading(jp);
2874  1653 if (t == JsonToken.VALUE_NULL) {
2875    // [JACKSON-643]: Ask JsonDeserializer what 'null value' to use:
2876  8 DeserializationContext ctxt = createDeserializationContext(jp,
2877    getDeserializationConfig());
2878  8 result = _findRootDeserializer(ctxt, valueType).getNullValue();
2879  1645 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2880  0 result = null;
2881    } else {
2882  1645 DeserializationConfig cfg = getDeserializationConfig();
2883  1645 DeserializationContext ctxt = createDeserializationContext(jp, cfg);
2884  1645 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
2885  1629 if (cfg.useRootWrapping()) {
2886  4 result = _unwrapAndDeserialize(jp, ctxt, cfg, valueType, deser);
2887    } else {
2888  1625 result = deser.deserialize(jp, ctxt);
2889    }
2890    }
2891    // Need to consume the token too
2892  1566 jp.clearCurrentToken();
2893  1566 return result;
2894    } finally {
2895  1654 try {
2896  1654 jp.close();
2897    } catch (IOException ioe) { }
2898    }
2899    }
2900   
2901    /**
2902    * Method called to ensure that given parser is ready for reading
2903    * content for data binding.
2904    *
2905    * @return First token to be used for data binding after this call:
2906    * can never be null as exception will be thrown if parser can not
2907    * provide more tokens.
2908    *
2909    * @throws IOException if the underlying input source has problems during
2910    * parsing
2911    * @throws JsonParseException if parser has problems parsing content
2912    * @throws JsonMappingException if the parser does not have any more
2913    * content to map (note: Json "null" value is considered content;
2914    * enf-of-stream not)
2915    */
 
2916  2011 toggle protected JsonToken _initForReading(JsonParser jp)
2917    throws IOException, JsonParseException, JsonMappingException
2918    {
2919    /* First: must point to a token; if not pointing to one, advance.
2920    * This occurs before first read from JsonParser, as well as
2921    * after clearing of current token.
2922    */
2923  2011 JsonToken t = jp.getCurrentToken();
2924  2011 if (t == null) {
2925    // and then we must get something...
2926  1981 t = jp.nextToken();
2927  1981 if (t == null) {
2928    /* [JACKSON-546] Throw mapping exception, since it's failure to map,
2929    * not an actual parsing problem
2930    */
2931  4 throw JsonMappingException.from(jp, "No content to map due to end-of-input");
2932    }
2933    }
2934  2007 return t;
2935    }
2936   
 
2937  4 toggle protected Object _unwrapAndDeserialize(JsonParser jp, DeserializationContext ctxt,
2938    DeserializationConfig config,
2939    JavaType rootType, JsonDeserializer<Object> deser)
2940    throws IOException, JsonParseException, JsonMappingException
2941    {
2942  4 String expName = config.getRootName();
2943  4 if (expName == null) {
2944  4 SerializedString sstr = _rootNames.findRootName(rootType, config);
2945  4 expName = sstr.getValue();
2946    }
2947  4 if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
2948  0 throw JsonMappingException.from(jp, "Current token not START_OBJECT (needed to unwrap root name '"
2949    +expName+"'), but "+jp.getCurrentToken());
2950    }
2951  4 if (jp.nextToken() != JsonToken.FIELD_NAME) {
2952  0 throw JsonMappingException.from(jp, "Current token not FIELD_NAME (to contain expected root name '"
2953    +expName+"'), but "+jp.getCurrentToken());
2954    }
2955  4 String actualName = jp.getCurrentName();
2956  4 if (!expName.equals(actualName)) {
2957  0 throw JsonMappingException.from(jp, "Root name '"+actualName+"' does not match expected ('"
2958    +expName+"') for type "+rootType);
2959    }
2960    // ok, then move to value itself....
2961  4 jp.nextToken();
2962  4 Object result = deser.deserialize(jp, ctxt);
2963    // and last, verify that we now get matching END_OBJECT
2964  4 if (jp.nextToken() != JsonToken.END_OBJECT) {
2965  0 throw JsonMappingException.from(jp, "Current token not END_OBJECT (to match wrapper object with root name '"
2966    +expName+"'), but "+jp.getCurrentToken());
2967    }
2968  4 return result;
2969    }
2970   
2971    /*
2972    /**********************************************************
2973    /* Internal methods, other
2974    /**********************************************************
2975    */
2976   
2977    /**
2978    * Method called to locate deserializer for the passed root-level value.
2979    */
 
2980  2009 toggle protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt,
2981    JavaType valueType)
2982    throws JsonMappingException
2983    {
2984    // First: have we already seen it?
2985  2009 JsonDeserializer<Object> deser = _rootDeserializers.get(valueType);
2986  2009 if (deser != null) {
2987  536 return deser;
2988    }
2989    // Nope: need to ask provider to resolve it
2990  1473 deser = ctxt.findRootValueDeserializer(valueType);
2991  1457 if (deser == null) { // can this happen?
2992  0 throw new JsonMappingException("Can not find a deserializer for type "+valueType);
2993    }
2994  1457 _rootDeserializers.put(valueType, deser);
2995  1457 return deser;
2996    }
2997   
2998    /**
2999    * @since 2.2
3000    */
 
3001  6 toggle protected void _verifySchemaType(FormatSchema schema)
3002    {
3003  6 if (schema != null) {
3004  6 if (!_jsonFactory.canUseSchema(schema)) {
3005  0 throw new IllegalArgumentException("Can not use FormatSchema of type "+schema.getClass().getName()
3006    +" for format "+_jsonFactory.getFormatName());
3007    }
3008    }
3009    }
3010    }